jquery datepicker动态禁用特定日期和日期

时间:2015-07-27 07:47:26

标签: php jquery json datepicker

我想从MySQL数据库记录中动态阻止特定日期和工作日。我已经在某种程度上做了,不能继续下去。

json_encode(array("days"=>$days_off,"dates"=>$resultarr))

以上将输出以下内容:

{"days":["0","1","1","1","1","1","0"],"dates":["2015-06-01","2015-06-02","2015-06-03","2015-06-04","2015-06-05"
,"2015-06-06","2015-07-09","2015-07-10","2015-07-28","2015-07-29","2015-07-30","2015-07-31"]}

在前端,以这种方式编写的jquery:

success: function(data){
    var dateToday = new Date();
    var ndata = $.parseJSON(data);
    if ($('#datepicker').length) $("#datepicker").datepicker({  
        minDate: dateToday, firstDay: 1, //endDate: '+0m',
        dateFormat: "DD d MM yy", showOtherMonths:false,
        beforeShowDay: function(date){ 
            var day = date.getDay();
            var selected = $("#datepicker").datepicker('getDate');
            return [ndata[day] !=0, ""];
        }                   
    });             
}

上面只会阻止几天(星期一 - 星期日)但不能阻止我从json数据上面得到的具体日期。

1 个答案:

答案 0 :(得分:0)

您需要检查日期是否与JSON中传递的日期相同。可以这样做:

beforeShowDay: function(date) { 

    //Check if it's a forbidden day of the week.
    var day = date.getDay();
    var okDay = (ndata.days[day] != 0);

    //Check if it's a forbidden date.
    var formatted_date = $.datepicker.formatDate('yy-mm-dd', date)
    var okDate = ($.inArray(formatted_date, ndata.dates) == -1);

    //Only return true if both day of week and date are allowed.
    return [okDay && okDate]

} 

请注意,我尚未测试此代码。此外,我从ndata[day]更改为ndata.days[day],因为这似乎更符合您的JSON,但我可能在那里错了。 Here是关于.inArray()的文档,here是关于datepicker.formatDate()的文档。