Search code examples
javascriptjquerydatepickerdate-rangepikaday

pikaday plugin 15 day between two date


I have a booking form and I need just two input .checkin and .checkout and that is why I have used datepicker with daterange everything is going ok almost one thing is how can I choose just 15 day between two date ?

by the way I'm using pikaday plugin MY CODE

$(document).on('focus', '.checkin, .checkout', function (){
    return new Pikaday({
   numberOfMonths: 2,
   field: this,
   format: "DD.MM.YYYY",
   minDate: new Date(),
   firstDay: 1,
   maxDate: new Date(2020, 12, 31),
   onSelect: function() {
    e = this.getDate();
   }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pikaday/1.5.1/pikaday.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/pikaday/1.5.1/css/pikaday.min.css" rel="stylesheet"/>
<div class="form">
<input type="text" class="checkin" placeholder="Checkin" />
<input type="text" class="checkout" placeholder="Checkout" />
</div>


Solution

  • You can restrict the minDate & maxDate of checkout datepicker based on the value of checkin datepicker.

    I have used getMaxDate() to get the max date for datepicker & if it is checkout picker, i am setting the maxdate as 15 + checkin date. Similarly i have use getMinDate() to get min date for datepicker & if it is checkout picker, i am setting the mindate as checkin date.

    $(document).on('focus', '.checkin, .checkout', function (){
        return new Pikaday({
       numberOfMonths: 2,
       field: this,
       format: "DD.MM.YYYY",
       minDate: getMinDate(this),
       firstDay: 1,
       maxDate: getMaxDate(this),
       onSelect: function() {
        e = this.getDate();
       }
      });
    });
    function getMaxDate(element){
      if(element.className=='checkout' && element.parentNode.querySelector('.checkin').value)
        return new Date(new Date(element.parentNode.querySelector('.checkin').value).getTime()+(15*24*60*60*1000));
    else
      return new Date(2020, 12, 31);
      }
    function getMinDate(element){
      if(element.className=='checkout' && element.parentNode.querySelector('.checkin').value)
        return new Date(element.parentNode.querySelector('.checkin').value);
      else
      return new Date();
      }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/pikaday/1.5.1/pikaday.min.js"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/pikaday/1.5.1/css/pikaday.min.css" rel="stylesheet"/>
    <div class="form">
    <input type="text" class="checkin" placeholder="Checkin" />
    <input type="text" class="checkout" placeholder="Checkout" />
    </div>