MrKrantz MrKrantz - 5 months ago 25
Javascript Question

Disable days in jQuery Datepicker depend on other properties in model MVC

I want to disable specific days of the week in

jQuery UI DatePicker
, depending on whether a value is true or false in the model submitted in @razor view .

I have a bool for each weekday . If a value is constructed so will the day be available in datepickern but if false, then the day will be disabled.

I looked around on different sides here but none of these options worked for me .
Here is my code :

$('#txtStartDate').datepicker({
defaultDate: '+1w',
numberOfMonths: 1,
showAnim: 'slide',
changeMonth: true,
changeYear: true,
showWeek: true,
dateFormat: "yy-mm-dd",
minDate: new Date(hidStartDate),
beforeShowDay: function(date) {
var day = date.getDay();

if (day == 1 && $('#hidMonday').val() == "True") {
return day;
}

if (day == 2 && $('#hidTuesday').val() == "True") {
return day;
}

if (day == 3 && $('#hidWednesday').val() == "True") {
return day;
}

if (day == 4 && $('#hidThursday').val() == "True") {
return day;
}

if (day == 5 && $('#hidFriday').val() == "True") {
return day;
}
},
});

$('#txtStartDate').css('clip', 'auto');


Once it has gone through about 5-6 days in the calendar , I get the following error in the console


" Jquery - ui.js : 9742 uncaught TypeError : Can not read property '0'
of undefined "


That said , I have looked around on the solution proposed here , but it may not work. This solution is based on the following proposal:

Disable specific days of the week on jQuery UI datepicker

Thanks in advance.

Answer

I checked your code in this fiddle

if (day == 1 && $('#hidMonday').val() == "True") {
            return day;
        }

        if (day == 2 && $('#hidTuesday').val() == "True") {
            return day;
        }

The error is coming when no day object is returned(when it is not getting into any of the if conditions). You can not simply not return anything Better return false if any of the conditions is not met

Comments