使用pikaday datepicker设置日期范围

时间:2017-02-20 07:14:53

标签: javascript jquery date datepicker date-range

我有一个预订表格,我只需要两个输入#checkin和#checkout,这就是为什么我使用datepicker和daterange一切正常几乎有一件事是我怎样才能在两个日期之间选择15天?

顺便说一句,我正在使用Pikaday datepicker

a.tag_ask, a.tag_show {
  background-color: #34a713;
  border: none;
  color: white;
}
$(document).ready(function() {

  $('.flexdatalist').flexdatalist({
    minLength: 0,
    searchContain: true,
  }).on('select:flexdatalist', function() {
    $('#checkin').trigger("click");
  });

  assignPicker = function(id, whenClosed) {
    if (typeof whenClosed !== 'function') {
      whenClosed = null;
    }

    return new Pikaday({
      numberOfMonths: 2,
      field: document.getElementById(id),
      format: "DD.MM.YYYY",
      minDate: new Date(),
      firstDay: 1,
      maxDate: new Date(2020, 12, 31),
      onSelect: function() {
        e = this.getDate();
      },
      onSelect: whenClosed
    });
  }

  assignPicker('checkin', function() {
    $('#checkout').trigger("click");
  });
  assignPicker('checkout', function() {
    $('#select').trigger("click");
  });

});
 body {
            padding: 30px;
        }
        input,
        select {
            width: 100%;
            padding: 10px;
            border: 1px solid #ccc;
        }

if you can check it out on codepen instead of stackoverflow snippet

1 个答案:

答案 0 :(得分:1)

您可以保存对结帐选择器的引用,然后将函数绑定到签入选择器的onSelect方法并相应地调整结帐日期选择器。您可以(也可能应该)加载Moment.js以使日期计算更容易。如果没有它,Pikaday(你正在使用)的format属性甚至都无法使用。

$(document).ready(function() {

  $('.flexdatalist').flexdatalist({
    minLength: 0,
    searchContain: true,
  }).on('select:flexdatalist', function() {
    $('#checkin').trigger("click");
  });

  assignPicker = function(id, whenClosed) {
    if (typeof whenClosed !== 'function') {
      whenClosed = null;
    }

    return new Pikaday({
      numberOfMonths: 2,
      field: document.getElementById(id),
      format: "DD.MM.YYYY",
      minDate: new Date(),
      firstDay: 1,
      maxDate: new Date(2020, 12, 31),
      onSelect: whenClosed
    });
  }

  var checkoutPicker = assignPicker('checkout', function() {
    $('#select').trigger("click");
  });

  var checkinPicker = assignPicker('checkin', function() {
    var maxDate = this.getMoment().add(15, 'days');
    checkoutPicker.setMaxDate(maxDate.toDate());
    checkoutPicker.setMinDate(this.getDate()); // min date of checkout = checkin
    checkoutPicker.setDate(null);
    $('#checkout').trigger("click"); // trigger checkout picker
  });

});

http://codepen.io/anon/pen/apgGpN