I am a novice using jQuery UI datepicker on a commerce site to set a shipping date. I want to populate the date input field with the first valid shipping date, which is defined as:
- later than today; and
- either a Monday or a Tuesday
(There are other conditions, but I am ignoring them for the moment.)
As I write this, and for the next few days, the correct value of this date is 8/8/2011.
Here is the page:
http://www.lolacookies.com/gifts/
Here is my code, which is not working. The commented part is what’s supposed to be doing the work. The value of the input is not being set at all; in previous attempts the date has been set to the value of minDate, but not to any other value.
$(document).ready(function(){
$(".datepicker").datepicker({
beforeShowDay: nonWorkingDates,
hideIfNoPrevNext: true,
numberOfMonths: 1,
minDate: "+1d",
maxDate: "+3M",
showAnim: "blind",
showOn: "both",
buttonImage: "/images/misc/calendar.png",
buttonImageOnly: true,
buttonText: "Select a date"
});
//set firstShippingDate to value of minDate
//we don't ship on same day, so minDate is today + 1d
var firstShippingDate = $( ".datepicker" ).datepicker( "option", "minDate" );
//we ship only on Monday and Tuesday, so test for that
var dayOfWeek = firstShippingDate.getDay();
//if it's not Monday or Tuesday, advance firstShippingDate by one day and test again
while ( dayOfWeek == 0 || dayOfWeek == 3 || dayOfWeek == 4 || dayOfWeek == 5 || dayOfWeek == 6 )
{
firstShippingDate.setTime(firstShippingDate.getTime() + 86400000);
dayOfWeek = firstShippingDate.getDay();
};
//should exit loop with firstShippingDate set to first Monday or Tuesday that's not today
//set datepicker to that firstShippingDate
$(".datepicker").datepicker( "setDate" , firstShippingDate );
function nonWorkingDates(date){
var day = date.getDay(), Sunday = 0, Monday = 1, Tuesday = 2, Wednesday = 3, Thursday = 4, Friday = 5, Saturday = 6;
var closedDates = [[06, 27, 2011], [06, 28, 2011], [06, 29, 2011], [07, 04, 2011]];
var closedDays = [[Sunday], [Wednesday], [Thursday], [Friday], [Saturday]];
for (var i = 0; i < closedDays.length; i++) {
if (day == closedDays[i][0]) {
return [false];
}
}
for (i = 0; i < closedDates.length; i++) {
if (date.getMonth() == closedDates[i][0] - 1 &&
date.getDate() == closedDates[i][1] &&
date.getFullYear() == closedDates[i][2]) {
return [false];
}
}
return [true];
}
});
You might want to checkout the DateJS library. It let’s you do cool stuff like this to get the next monday:
So in your case, you can do something like this to get the next monday or tuesday: