0

Using jQuery DatePicker, I'd like to ensure that the departure date is at least 1 day after the arrival date. The closest I've managed to get to this is to ensure that the departure date is on the same day as the arrival date (I just couldn't figure out how to add 'selectedDate + 1 day' in the JS). I'd appreciate any help with this, thanks.

Here's my JS:

$(".datepicker_arrival").datepicker({
  dateFormat: 'dd/mm/yy',
  minDate: new Date(),
  onSelect: function(dateText, inst) {
    if($('.datepicker_departure').val() == '') {
      var current_date = $.datepicker.parseDate('dd/mm/yy', dateText);
      current_date.setDate(current_date.getDate()+1);
      $('.datepicker_departure').datepicker('setDate', current_date);
    }
  },
  onClose: function( selectedDate ) {
    $( ".datepicker_departure" ).datepicker( "option", "minDate", selectedDate );
  }
});

$(".datepicker_departure").datepicker({
  dateFormat: 'dd/mm/yy',
  minDate: new Date(),
  onClose: function( selectedDate ) {
    $( ".datepicker_arrival" ).datepicker( "option", "maxDate", selectedDate );
  }
});

Here's my HTML:

<input type="text" name="arrival" class="datepicker datepicker_arrival textfield" placeholder="Arrival Date" />

<input type="text" name="departure" class="datepicker datepicker_departure textfield" placeholder="Departure Date" />
Stephen
  • 553
  • 3
  • 12
  • 23

1 Answers1

2

You can pass the datepicker object in the onClose method:

http://api.jqueryui.com/datepicker/#option-onClose

Consequently, this should work fine:

$(".datepicker_arrival").datepicker({
  dateFormat: 'dd/mm/yy',
  minDate: new Date(),
  onSelect: function(dateText, inst) {
    if($('.datepicker_departure').val() == '') {
      var current_date = $.datepicker.parseDate('dd/mm/yy', dateText);
      current_date.setDate(current_date.getDate()+1);
      $('.datepicker_departure').datepicker('setDate', current_date);
    }
  },
  onClose: function( selectedDate, test) {
     var  MyDateString = ('0' + (parseInt(test.selectedDay)+1)).slice(-2) + '/'
             + ('0' + (test.selectedMonth+1)).slice(-2) + '/'
             + test.selectedYear;
      $( ".datepicker_departure" ).datepicker( "option", "minDate", MyDateString);
  }
});

Fiddle:

http://jsfiddle.net/SpAm/9mSxk/1/

Credit for the padding idea comes from the accepted answer by user113716 in this thread:

Javascript add leading zeroes to date

Community
  • 1
  • 1
MasNotsram
  • 2,105
  • 18
  • 28
  • For info, I've since noticed a bug with this, so just posted a follow-up question here: http://stackoverflow.com/questions/16854506/jquery-datepicker-dates-have-to-be-one-day-apart-but-theres-a-bug-if-the-sta – Stephen May 31 '13 at 09:51
  • I've commented in that question, but this should hopefully fix it: http://jsfiddle.net/9mSxk/3/ – MasNotsram May 31 '13 at 13:24