Disable all Sundays and some specific dates in jQuery UI datepicker

69 Views Asked by At

I am trying to disable all Sundays and some specific dates in jQuery UI datepicker. These conditions, together, don't work in my code. Only sundays are getting disabled. Here is the code

var array = [, '2024-01-07', '2024-01-08', '2024-01-09', '2024-01-10']
$("#datepicker").datepicker({
  beforeShowDay: function(date) {
    var day = date.getDay();
    var string = jQuery.datepicker.formatDate('yy-mm-dd', date);
    return [(day != 0), array.indexOf(string) == -1]
  }
});

I want all Sundays and some dates to be disabled in datepicker.

4

There are 4 best solutions below

0
Salman A On BEST ANSWER

It needs to be:

// date is not a sunday and
// date is not present in the array
return [day !== 0 && array.indexOf(string) === -1];

Note that you just need to set the 0th item of the returned array (docs).

0
Shivang Rathod On

Could you please update this line

return [(day!=0), array.indexOf(string) == -1 ]

with this

return [!((date.getDay() === 0) || array.includes(string)), true];
0
vijay pancholi On

See Demo

Disable all Sundays and some specific dates in datepicker using jquery

$(function() {
  var holidays = ['2024-1-7','2024-1-8','2024-1-9','2024-1-10'];
  function DisableDate(date) {
    var day = date.getDay();
    if (day != 0) {
      var d = date.getDate();
      var m = date.getMonth();
      var y = date.getFullYear();
      for (i = 0; i < holidays.length; i++) {
        if($.inArray((y) + '-' + (m+1) + '-' + d, holidays) != -1) {
          return [false];
        }
      }
      return [true];
    } else {
      return [day != 0, ''];
    }
  }

  $('#datepicker').datepicker({
    onClose: function(dateText, inst) { 
        $(this).attr("disabled", false);
    },
    beforeShow: function(input, inst) {
      $(this).attr("disabled", true);
    },
    beforeShowDay: DisableDate,
    minDate: 0,
    dateFormat: 'yy-mm-dd',
  });
});
0
Md Naseem On

To disable both all Sundays and specific dates in the jQuery datepicker, you can modify your code as follows:

var array = ['2024-01-07', '2024-01-08', '2024-01-09', '2024-01-10'];

$("#datepicker").datepicker({
  beforeShowDay: function (date) {
    var day = date.getDay();
    var string = jQuery.datepicker.formatDate('yy-mm-dd', date);
    return [(day !== 0 && array.indexOf(string) === -1)];
  }
});

The key change here is to make sure that you return true for the days you want to enable. In this case, the condition in return checks if the day is not Sunday (day !== 0) and if the date is not in the specified array.

This way, both Sundays and the specific dates in the array will be disabled in the datepicker. The datepicker will only allow the selection of non-Sundays that are not in the specified array.