Disable specific days in a Jquery UI datepicker
I'm building a booking system and wanted to use the datepicker from the jQuery UI library. The datepicker allows you to define a range of dates that can be selected (using minDate and maxDate options), but doesn't have a way to make dates within the range unavailable. For a booking system I need to be able to show which dates were already booked and disable them. After reading through the documentation I found there is an beforeShowDay event, this is what the docs say:
The function takes a date as a parameter and must return an array with [0] equal to true/false indicating whether or not this date is selectable, [1] equal to a CSS class name(s) or '' for the default presentation, and [2] an optional popup tooltip for this date. It is called for each day in the datepicker before it is displayed.
This is really useful, as we can use it to check each date and return an array. The first element of the array is a flag set to true or false which makes the date disabled or selectable.
Here is an example of it in action:
<form action="somescript.cfm" method="post">
<table summary="Booking form">
<tr>
<td><label for="startdate">Check In Date:</label></td>
<td><input type="text" id="startdate" name="startdate" value="" /></td>
</tr>
<tr>
<td><label for="enddate">Check Out Date:</label></td>
<td><input type="text" id="enddate" name="enddate" value="" /></td>
</tr>
<tr>
<td>&nsp;</td>
<td><input type="submit" id="submit" name="submit" value="submit" /></td>
</tr>
</table>
</form>
</cfoutput>
<script type="text/javascript">
// <![CDATA[
$(function(){
var bookedDays = ["2010-6-10","2010-6-12","2010-6-14"];
function assignCalendar(id){
$('<div class="calendar" />')
.insertAfter( $(id) )
.datepicker({
dateFormat: 'dd-mm-yy',
minDate: new Date(),
maxDate: '+1y',
altField: id,
beforeShowDay: isAvailable })
.prev().hide();
}
function isAvailable(date){
var dateAsString = date.getFullYear().toString() + "-" + (date.getMonth()+1).toString() + "-" + date.getDate();
var result = $.inArray( dateAsString, bookedDays ) ==-1 ? [true] : [false];
return result
}
assignCalendar('#startdate');
assignCalendar('#enddate');
});
// ]]>
</script>
You will of course need the jQuery UI library to make this work!
- Posted in:
- jQuery


Comment by Ben Nadel – June 10, 2010
How do you cater for non-JS users, or is this a Intranet app so you don't have to worry about people not using JS?
Comment by Sebastiaan – June 11, 2010
@Sebastiaan - if the user doesn't have JS then they see the text boxes (which are hidden if they do have JS). I then check the dates when they submit the form server side.
Comment by John Whish – June 11, 2010
Comment by Martin – November 22, 2010
tokenposts.blogspot.com/2011/05/jquery-datepicker-disable-specific.html
Comment by Tokes – May 13, 2011