1
votes

I'm trying to set the minDate of a datepicker using the date that the user picked from another datepicker (i.e. check-in/check-out dates).

Here's my code:

var checkin = document.getElementById('check-in');
var checkout = document.getElementById('check-out');

var dateField;

$('#check-in').datepicker({
  onSelect: function (date) {
    dateField = $(this).val();
    console.log(date);
  },
  altField: '#actual-checkin-date',
  altFormat: 'mm/dd/yy',
  dateFormat: 'dd/mm/yy',
  minDate: 0
});

$('#check-out').datepicker({
  altField: '#actual-checkout-date',
  altFormat: 'mm/dd/yy',
  dateFormat: 'dd/mm/yy',
  minDate: new Date(dateField)
});

checkin.onclick = function () {
  $('#check-in').datepicker();
};

checkout.onclick = function () {
  $('#check-out').datepicker();
  console.log($('#check-out').datepicker("option", "minDate"));
}

I can log the date from the check-in datepicker correctly, but I can't set that date as minDate of the check-out datepicker. The last log, the one in the last datapicker, shows me "Invalid Date", while the log in the first datapicker shows me the date in the dd/mm/yy format.

What am I doing wrong?

Thanks for the help!

1

1 Answers

1
votes

You're running into two issues here: 1) when you create your check-out datepicker is created your dataField is not defined yet (it gets set once you select a data in your check-in datepicker)

2) you are not creating a valid Date - you can access the Date of a datepicker by using $('#check-in').datepicker("getDate")

take a look at this fiddle: http://jsfiddle.net/nerL43s5/ to see it in action.

$('#check-in').datepicker({
  onSelect: function(date) {
    console.log(date );
    // now you have a date you can set as the minDate:
    $('#check-out').datepicker('option', 'minDate', $('#check-in').datepicker('getDate'));
    console.log($('#check-out').datepicker('option', 'minDate'));
  },
  altField: '#actual-checkin-date',
  altFormat: 'mm/dd/yy',
  dateFormat: 'dd/mm/yy',
  minDate: 0
});