将jQuery UI datepicker设置为第一个定义为有效的日期

时间:2011-08-02 17:54:51

标签: jquery-ui datepicker jquery-ui-datepicker

我是新手,在商业网站上使用jQuery UI datepicker设置发货日期。我想用第一个有效发货日期填充日期输入字段,该日期定义为:

  • 晚于今天;和
  • 周一或周二

(还有其他条件,但我暂时忽略它们。)

在我写这篇文章时,在接下来的几天里,这个日期的正确值是8/8/2011。

以下是页面:

http://www.lolacookies.com/gifts/

这是我的代码,它不起作用。评论部分是应该做的工作。输入的值根本没有设置;在之前的尝试中,日期已设置为minDate的值,但不是任何其他值。

$(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];
}


});

1 个答案:

答案 0 :(得分:0)

您可能想要结帐DateJS库。它让你做这样很酷的事情来获得下一个星期一:

Date.today().next().monday();

所以在你的情况下,你可以做这样的事情来获得下一个星期一或星期二:

if (Date.today().is().monday()) {
  firstShippingDate = Date.today().next().tuesday();
} else {
  firstShippingDate = Date.today().next().monday();
}