vendredi 13 février 2015

Jquery Datepicker - prevent select in range unavailable dates


I have 2 datepickers (From date, to date) or when a people arive at my hotel and when he leaves. What i want to achieve is not to let the user select a range that includes unavailable dates.


For example:


Today is 13.02.2015, a people want to reserve from 15.02.2015 to 23.02.2015 but the dates 19-02-2015, 20-02-2015 are already reserved. So i want to disable all the fields starting from 19.02.2015 meaning that he can select only from 15.02.2015 to 18.02.2015. It depends on what date he picks and he can book only to the first unavailable date, not next to that.


How can I achieve this?


This is my html code:



<label for="from">From</label>
<input type="text" id="from" name="from">
<label for="to">to</label>
<input type="text" id="to" name="to">


This is the javascript code



var unavailableDates = ["19-2-2015", "20-2-2015", "23-2-2015", "24-2-2015"]

function unavailable(date) {
dmy = date.getDate() + "-" + (date.getMonth() + 1) + "-" + date.getFullYear();
if (jQuery.inArray(dmy, unavailableDates) == -1) {
return [true, ""];
} else {
return [false, "", "Unavailable"];
}
}

$(function() {
$( "#from" ).datepicker({
defaultDate: "+1w",
changeMonth: true,
beforeShowDay: unavailable,
numberOfMonths: 1,
dateFormat: 'dd/mm/yy',
onClose: function( selectedDate ) {
$( "#to" ).datepicker( "option", "minDate", selectedDate );
}
});

$( "#to" ).datepicker({
defaultDate: "+1w",
changeMonth: true,
beforeShowDay: unavailable,
numberOfMonths: 1,
dateFormat: 'dd/mm/yy',
onClose: function( selectedDate ) {
$( "#from" ).datepicker( "option", "maxDate", selectedDate );
}
});
});


And here is my jsfiddle working example





Aucun commentaire:

Enregistrer un commentaire