Thursday, November 25, 2010

9:37 PM
One project I'm currently working on requires jQuery. The project also features a datepicker for requesting a visit to their location. jQuery UI's DatePicker plugin was the natural choice and it does a really nice job. One challenge I encountered was the need to prevent specific days from being picked. Here's the jQuery JavaScript I used to accomplish that.



The jQuery JavaScript


/* create an array of days which need to be disabled */
var disabledDays = ["2-21-2010","2-24-2010","2-27-2010","2-28-2010","3-3-2010","3-17-2010","4-2-2010","4-3-2010","4-4-2010","4-5-2010"];

/* utility functions */
function nationalDays(date) {
var m = date.getMonth(), d = date.getDate(), y = date.getFullYear();
//console.log('Checking (raw): ' + m + '-' + d + '-' + y);
for (i = 0; i < disabledDays.length; i++) {
if($.inArray((m+1) + '-' + d + '-' + y,disabledDays) != -1 || new Date() > date) {
//console.log('bad:  ' + (m+1) + '-' + d + '-' + y + ' / ' + disabledDays[i]);
return [false];
}
}
//console.log('good:  ' + (m+1) + '-' + d + '-' + y);
return [true];
}
function noWeekendsOrHolidays(date) {
var noWeekend = jQuery.datepicker.noWeekends(date);
return noWeekend[0] ? nationalDays(date) : noWeekend;
}

/* create datepicker */
jQuery(document).ready(function() {
jQuery('#date').datepicker({
minDate: new Date(2010, 0, 1),
maxDate: new Date(2010, 5, 31),
dateFormat: 'DD, MM, d, yy',
constrainInput: true,
beforeShowDay: noWeekendsOrHolidays
});
});


The base code is taken from this forum post. You'll note that I created an array of dates in string format which also accommodates for comparing year.

I'd like to see jQuery UI implement a standard way of disabling days. Their DatePicker is very nice though so I can't complain too much!

0 comments: