Search code examples
javascriptjquerydatepickerbootstrap-datepicker

Bootstrap date picker, enable a few days in daysOfWeekDisabled


Bootstrap datePicker allows me to pass a parameter to disabled an specific day of the week. Like this:

datePicker.datepicker({
    daysOfWeekDisabled: weekendDays
});

I want to be able to enable an specific date on this disabled list. I was trying to use the beforeShowDay option, but it's seems that I can disable the dates there but I can't enable.

According to the documentation I can return a boolen to point if I want the value to be seleced, or I can return a object with enabled property, like this:

datePicker.datepicker({
    daysOfWeekDisabled: weekendDays,
    beforeShowDay: function (date) {
        var string = jQuery.datepicker.formatDate('yy-mm-dd', date);
        if(workingDays.indexOf(string) > -1){
            return {enabled: true, classes: "test"};
        }
    }
});

I can add the class using the beforeShowDay, I can disabled the date. But I can't enable it.

Does anyone know how I can do that?


Solution

  • I would suggest combining both the operations of disabling the weekend dates and enabling certain dates into one.

    For example:

    var dates = ["19/07/2020"];
    
    function disableDates(date) {
        let shouldDisable = false;
        
        // Disable dates if they are weekends
        if(date.getDay() == 0 || date.getDay() == 6){
          shouldDisable = true;
        }
        
        // Check if date is mentioned for enabling in the dates array. 
        var string = jQuery.datepicker.formatDate('dd/mm/yy', date);
        return [ !shouldDisable || dates.indexOf(string) != -1];
    }
    
    $(function() {
         $("#date").datepicker({
             beforeShowDay: disableDates
         });
    });
    

    This will provide more control over enabling and disabling dates using one single function.

    Sample fiddle: https://jsfiddle.net/idhruvs/wdkprbsL/120/