jQuery Date Picker - 如果用户没有选择开始日期,则禁用所有结束日期

时间:2018-03-23 12:14:42

标签: jquery datepicker

在我的日期选择器中,我有一些约束

  1. 结束日期不应早于开始日期-Done
  2. 现在我的问题是用户不应该选择结束日期而不选择开始日期
  3. 我的Jquery for datepicker:

    var dateToday = new Date(); 
    $( function() {
      $( "#datepicker1" ).datepicker({
        changeMonth: true,
        changeYear: true,
        dateFormat:'dd-M-yy',
        //   minDate: dateToday,
        onClose: function (selected) {
          $("#end").datepicker("option", "minDate", selected);
        }
      });
      $( "#end" ).datepicker({
        changeMonth: true,
        changeYear: true,
        dateFormat:'dd-M-yy',
        // minDate: dateToday,
        onClose: function (selected) {
          $("#datepicker1").datepicker("option", "maxDate", selected);
        }
      });
    }); 
    

2 个答案:

答案 0 :(得分:3)

请参阅:

中的更改
onClose: function (selected) {
  if(selected.length <= 0) {
      // selected is empty
      $("#end").datepicker('disable')
  } else {
      $("#end").datepicker('enable');
  }
  $("#end").datepicker("option", "minDate", selected);
}

在这里演示给你一个想法。满足您的需求。

var dateToday = new Date(); 
$( function() {
  $( "#datepicker1" ).datepicker({
    changeMonth: true,
    changeYear: true,
    dateFormat:'dd-M-yy',
    //   minDate: dateToday,
    onClose: function (selected) {
      if(selected.length <= 0) {
          // selected is empty
          $("#end").datepicker('disable');
      } else {
          $("#end").datepicker('enable');
      }
      $("#end").datepicker("option", "minDate", selected);
    }
  });
  $( "#end" ).datepicker({
    changeMonth: true,
    changeYear: true,
    dateFormat:'dd-M-yy',
    // minDate: dateToday,
    onClose: function (selected) {
      if(selected.length <= 0) {
          // selected is empty
          $("#datepicker1").datepicker('disable');
      } else {
          $("#datepicker1").datepicker('enable');
      }
      $("#datepicker1").datepicker("option", "maxDate", selected);
    }
  });
}); 
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/datepicker/0.6.4/datepicker.css">
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>



<input id="datepicker1" type="text">
<input id="end" type="text">

答案 1 :(得分:1)

首先,您应该默认禁用#end datepicker。然后修改onClick的{​​{1}}处理程序,如下所示:

#datepicker1