jQuery-UI的datepicker的默认日期范围

时间:2017-07-14 13:37:35

标签: javascript jquery html jquery-ui

我正在使用jQuery-UI创建日期范围字段。我想要做的是将我的StartDate默认为今天的日期减去七天,并将我的EndDate默认为“今天”日期。如果用户想要更改日期,仍允许更改日期。同时不允许用户选择日期(今天的日期之后)。使用jQuery-UI的datepicker可以实现这一切吗?

<script>
  $( function() {
    var dateFormat = "mm/dd/yy",
      from = $( "#StartDate" )
        .datepicker({
          defaultDate: "+1w",
          changeMonth: true,
          numberOfMonths: 1
        })
        .on( "change", function() {
          to.datepicker( "option", "minDate", getDate( this ) );
        }),
      to = $( "#EndDate" ).datepicker({
        defaultDate: "+1w",
        changeMonth: true,
        numberOfMonths: 1
      })
      .on( "change", function() {
        from.datepicker( "option", "maxDate", getDate( this ) );
      });

    function getDate( element ) {
      var date;
      try {
        date = $.datepicker.parseDate( dateFormat, element.value );
      } catch( error ) {
        date = null;
      }

      return date;
    }
  } );
  </script>

<span class="srch_title" for="StartDate">From</span>
<input type='text' name="StartDate" id="StartDate" value="" required/>

<span class="srch_title" for="EndDate">To</span>
<input type='text' name="EndDate" id="EndDate" value="" required/>

https://jsfiddle.net/bobrierton/fdLy2n12/

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:1)

如果我正确理解标准,则以下内容应该是预期的

$(function() {
  var today = new Date(),
    weekAgo = new Date(),
    $from = $("#StartDate"),
    $to = $("#EndDate");

  weekAgo.setDate(today.getDate() - 7);

  $from.datepicker({   
    maxDate: today,
    onSelect: function(dateText) {
      $to.datepicker("option", "minDate", dateText);
    }
  }).datepicker('setDate', weekAgo);

  $to.datepicker({
    maxDate: today,
    minDate: weekAgo,
    onSelect: function(dateText) {
      $from.datepicker("option", "maxDate", dateText);
    }
  }).datepicker('setDate', today);

});

不确定from是否需要minDate

DEMO