jQuery UI Datepicker : disabling specific dates
Here’s another demo of the jQuery UI Datepicker plugin, here disabling specific dates. This is actually pretty straightforward. Here’s the basic javascript:
$(function() {
$( "#pickdate" ).datepicker({
dateFormat: 'dd MM yy',
beforeShowDay: checkBadDates
});
}
So here I’m just setting the date format and using the beforeShowDay event to call a function to check if any of the dates should be disabled:
var $myBadDates = new Array("10 October 2010","21 November 2010","12 December 2010","13 January 2011","14 February 2011","15 March 2011");
function checkBadDates(mydate){
var $return=true;
var $returnclass ="available";
$checkdate = $.datepicker.formatDate('dd MM yy', mydate);
for(var i = 0; i < $myBadDates.length; i++)
{
if($myBadDates[i] == $checkdate)
{
$return = false;
$returnclass= "unavailable";
}
}
return [$return,$returnclass];
}
Here I'm just populating a local array with my list of excluded dates, but this could esasily be populated from a database lookup, for example. My checkBadDates function is passed each date of the month to be displayed, with the date automatically passed as the argument by datepicker. My function sets some initial values, and then searches the array for a matched bad date - and if found amends the return values appropriately. Note I have to set the format of the date to be checked again so it matches that of my array - it doesn't use the date format I've set earlier.
And really, that's all there is to it. Here's a demo - I've used the class returned by the checkBadDate function to set a green/red background colour for available/unavailable dates. Tested in IE6, IE7, IE8, Firefox3, Chrome, Opera 9, Opera 10 and Safari 4, all on Win/XP, and Safari 5 on Mac OS X/Snow Leopard. View the source to see the css and html. Feel free to leave comments, questions and suggestions for improvement below.
I have another, more complex, demo here which restricts the use to selecting weeks only.