I’m having a problem with the jQuery UI Datepicker, specifically getting it to show free days based on a ajax query and json response.
The first thing I learned was that $.getJSON could in some cases execute after the $(document).ready function had completed, therefore the data would not be available before the datepicker was rendered.
So instead I binded the datepicker within the ajax success callback, and whilst the day highlighting works in Chrome browser, it doesn’t work in IE or FF at all (the datepicker works but the highlighting doesn’t).
I will try and provide a minimal “working” example:
// sample json response
// [{"date":"2011-4-01","type":"free"}]
// declare freeDays global arrays
var freeDays = [];
$(document).ready(function() {
// perform initial json request for day usage
fetchDayUsage();
});
// query for day usage in datepicker - year, month are passed by the datepicker object
function fetchDayUsage(year, month)
{
var start_date = '';
// if a month and year were supplied, build a start_date in yyyy-mm-dd format
if (year != undefined && month != undefined) {
start_date = year +'-';
start_date += month +'-';
start_date += '01';
}
$.ajax({
async: false,
url: "ajax.todos?action=fetchDayUsage&start_date="+ start_date,
dataType: "json",
success: function(data) {
// loop over json response
$.each(data, function(index, value) {
// add to freeDays array
switch (value.type) {
case 'free':
freeDays.push(value.date); // add this date to the freeDays array
break;
}
});
// datepicker popout for date due on create new to-do
$("#datepicker").datepicker({
changeMonth: true,
changeYear: true,
showOtherMonths: true,
selectOtherMonths: true,
//numberOfMonths: 2,
dateFormat: 'DD, d MM, yy',
altField: '#date_due',
altFormat: 'yy-mm-dd',
beforeShowDay: highlightDays,
onChangeMonthYear: fetchDayUsage,
firstDay: 1 // rows starts on Monday
});
}
});
}
// runs for every day displayed in datepicker, adds class and tooltip if matched to days in freeDays array
function highlightDays(date)
{
// loop free days
for (var a=0; a<freeDays.length; a++) {
if (new Date(freeDays[a]).toString() == date.toString()) {
return [true, 'free-day', 'no to-do items due']; // [0] = true | false if this day is selectable, [1] = class to add, [2] = tooltip to display
}
}
return [true, ''];
}
By the way I had to set async to false to get consistent results even in chrome.
In firebug I can see the request and response which both look fine, so it appears the problem is with highlightDays. Is there any reason why the toString line would be treated differently across browsers?