jQuery: enable or disable weekdays in the Bootstrap datepicker plugin

jQuery: enable or disable weekdays in the Bootstrap datepicker plugin

You can enable or disable specific weekdays in the Bootstrap datepicker plugin.

You can enable or disable specific weekdays in the Bootstrap datepicker plugin.

Suppose that you want to allow users to choose only dates with a specific weekday (this is quite common in booking plugins). The datepicker plugin features the datesDisabled option. This option is an array of date strings which must use the same format chosen with the format option.

So you can write the following code:


"use strict";

$.filterDates = function( filterDay ) {
  var oneDayInMs = 86400000;
  var dates = [];
  var start = new Date();
  for( var i = 1; i <= 365; i++ ) {
      var aDay = oneDayInMs * i;
      var tsDay = start.getTime() + aDay;
      var nDate = new Date( tsDay );
      if( nDate.getDay() !== parseInt( filterDay, 10 ) ) {
        var yy = nDate.getFullYear().toString();
        var mm = ( ( nDate.getMonth() + 1 ) < 10 ) ? '0' + ( nDate.getMonth() + 1 ).toString() : ( nDate.getMonth() + 1 ).toString();
        var dd = ( nDate.getDate() < 10 ) ? '0' + ( nDate.getDate() ).toString() : ( nDate.getDate() ).toString();
        var date = yy + "-" + mm + "-" + dd;
        dates.push( date );
      }
  }
  return dates;
};

Weekdays fall in the range between 0 (Sunday) and 6 (Saturday) in JavaScript. For example:


"use strict";

$( "#date" ).datepicker({
     format: "yy-mm-dd",
     datesDisabled: $.filterDates( 1 ) // Only Mondays allowed
});

Documentation

bootstrap-datepicker