[javascript] Can the jQuery UI Datepicker be made to disable Saturdays and Sundays (and holidays)?

I use a datepicker for choosing an appointment day. I already set the date range to be only for the next month. That works fine. I want to exclude Saturdays and Sundays from the available choices. Can this be done? If so, how?

This question is related to javascript jquery jquery-ui jquery-ui-datepicker

The answer is


In the latest Bootstrap 3 version (bootstrap-datepicker.js) beforeShowDay expects a result in this format:

{ enabled: false, classes: "class-name", tooltip: "Holiday!" }

Alternatively, if you don't care about the CSS and tooltip then simply return a boolean false to make the date unselectable.

Also, there is no $.datepicker.noWeekends, so you need to do something along the lines of this:

var HOLIDAYS = {  // Ontario, Canada holidays
    2017: {
        1: { 1: "New Year's Day"},
        2: { 20: "Family Day" },
        4: { 17: "Easter Monday" },
        5: { 22: "Victoria Day" },
        7: { 1: "Canada Day" },
        8: { 7: "Civic Holiday" },
        9: { 4: "Labour Day" },
        10: { 9: "Thanksgiving" },
        12: { 25: "Christmas", 26: "Boxing Day"}
    }
};

function filterNonWorkingDays(date) {
    // Is it a weekend?
    if ([ 0, 6 ].indexOf(date.getDay()) >= 0)
        return { enabled: false, classes: "weekend" };
    // Is it a holiday?
    var h = HOLIDAYS;
    $.each(
        [ date.getYear() + 1900, date.getMonth() + 1, date.getDate() ], 
        function (i, x) {
            h = h[x];
            if (typeof h === "undefined")
                return false;
        }
    );
    if (h)
        return { enabled: false, classes: "holiday", tooltip: h };
    // It's a regular work day.
    return { enabled: true };
}

$("#datePicker").datepicker({ beforeShowDay: filterNonWorkingDays });

The solution here that everyone likes seems to very intense... personally I think it's much easier to do something like this:

       var holidays = ["12/24/2012", "12/25/2012", "1/1/2013", 
            "5/27/2013", "7/4/2013", "9/2/2013", "11/28/2013", 
            "11/29/2013", "12/24/2013", "12/25/2013"];

       $( "#requestShipDate" ).datepicker({
            beforeShowDay: function(date){
                show = true;
                if(date.getDay() == 0 || date.getDay() == 6){show = false;}//No Weekends
                for (var i = 0; i < holidays.length; i++) {
                    if (new Date(holidays[i]).toString() == date.toString()) {show = false;}//No Holidays
                }
                var display = [show,'',(show)?'':'No Weekends or Holidays'];//With Fancy hover tooltip!
                return display;
            }
        });

This way your dates are human readable. It's not really that different it just makes more sense to me this way.


In the latest Bootstrap 3 version (bootstrap-datepicker.js) beforeShowDay expects a result in this format:

{ enabled: false, classes: "class-name", tooltip: "Holiday!" }

Alternatively, if you don't care about the CSS and tooltip then simply return a boolean false to make the date unselectable.

Also, there is no $.datepicker.noWeekends, so you need to do something along the lines of this:

var HOLIDAYS = {  // Ontario, Canada holidays
    2017: {
        1: { 1: "New Year's Day"},
        2: { 20: "Family Day" },
        4: { 17: "Easter Monday" },
        5: { 22: "Victoria Day" },
        7: { 1: "Canada Day" },
        8: { 7: "Civic Holiday" },
        9: { 4: "Labour Day" },
        10: { 9: "Thanksgiving" },
        12: { 25: "Christmas", 26: "Boxing Day"}
    }
};

function filterNonWorkingDays(date) {
    // Is it a weekend?
    if ([ 0, 6 ].indexOf(date.getDay()) >= 0)
        return { enabled: false, classes: "weekend" };
    // Is it a holiday?
    var h = HOLIDAYS;
    $.each(
        [ date.getYear() + 1900, date.getMonth() + 1, date.getDate() ], 
        function (i, x) {
            h = h[x];
            if (typeof h === "undefined")
                return false;
        }
    );
    if (h)
        return { enabled: false, classes: "holiday", tooltip: h };
    // It's a regular work day.
    return { enabled: true };
}

$("#datePicker").datepicker({ beforeShowDay: filterNonWorkingDays });

For Saturday and Sunday You can do something like this

             $('#orderdate').datepicker({
                               daysOfWeekDisabled: [0,6]
                 });

$("#selector").datepicker({ beforeShowDay: highlightDays });

...

var dates = [new Date("1/1/2011"), new Date("1/2/2011")];

function highlightDays(date) {

    for (var i = 0; i < dates.length; i++) {
        if (date - dates[i] == 0) {
            return [true,'', 'TOOLTIP'];
        }
    }
    return [false];

}

In this version, month, day, and year determines which days to block on the calendar.

$(document).ready(function (){
  var d         = new Date();
  var natDays   = [[1,1,2009],[1,1,2010],[12,31,2010],[1,19,2009]];

  function nationalDays(date) {
    var m = date.getMonth();
    var d = date.getDate();
    var y = date.getFullYear();

    for (i = 0; i < natDays.length; i++) {
      if ((m == natDays[i][0] - 1) && (d == natDays[i][1]) && (y == natDays[i][2]))
      {
        return [false];
      }
    }
    return [true];
  }
  function noWeekendsOrHolidays(date) {
    var noWeekend = $.datepicker.noWeekends(date);
      if (noWeekend[0]) {
        return nationalDays(date);
      } else {
        return noWeekend;
    }
  }
  $(function() { 
    $(".datepicker").datepicker({

      minDate: new Date(d.getFullYear(), 1 - 1, 1),
      maxDate: new Date(d.getFullYear()+1, 11, 31),

      hideIfNoPrevNext: true,
      beforeShowDay: noWeekendsOrHolidays,
     });
  });
});

The datepicker has this functionality built in!

$( "#datepicker" ).datepicker({
  beforeShowDay: $.datepicker.noWeekends
});

http://api.jqueryui.com/datepicker/#utility-noWeekends


The solution here that everyone likes seems to very intense... personally I think it's much easier to do something like this:

       var holidays = ["12/24/2012", "12/25/2012", "1/1/2013", 
            "5/27/2013", "7/4/2013", "9/2/2013", "11/28/2013", 
            "11/29/2013", "12/24/2013", "12/25/2013"];

       $( "#requestShipDate" ).datepicker({
            beforeShowDay: function(date){
                show = true;
                if(date.getDay() == 0 || date.getDay() == 6){show = false;}//No Weekends
                for (var i = 0; i < holidays.length; i++) {
                    if (new Date(holidays[i]).toString() == date.toString()) {show = false;}//No Holidays
                }
                var display = [show,'',(show)?'':'No Weekends or Holidays'];//With Fancy hover tooltip!
                return display;
            }
        });

This way your dates are human readable. It's not really that different it just makes more sense to me this way.


If you don't want the weekends to appear at all, simply:

CSS

th.ui-datepicker-week-end,
td.ui-datepicker-week-end {
    display: none;
}

This version of code will make u to get the holiday dates from the sql database and disable the specified date in the UI Datepicker


$(document).ready(function (){
  var holiDays = (function () {
    var val = null;
    $.ajax({
        'async': false,
        'global': false,
        'url': 'getdate.php',
        'success': function (data) {
            val = data;
        }
    });
    return val;
    })();
  var natDays = holiDays.split('');

  function nationalDays(date) {
    var m = date.getMonth();
    var d = date.getDate();
    var y = date.getFullYear();

    for (var i = 0; i ‘ natDays.length-1; i++) {
    var myDate = new Date(natDays[i]);
      if ((m == (myDate.getMonth())) && (d == (myDate.getDate())) && (y == (myDate.getFullYear())))
      {
        return [false];
      }
    }
    return [true];
  }

  function noWeekendsOrHolidays(date) {
    var noWeekend = $.datepicker.noWeekends(date);
      if (noWeekend[0]) {
        return nationalDays(date);
      } else {
        return noWeekend;
    }
  }
  $(function() { 
    $("#shipdate").datepicker({
      minDate: 0,
      dateFormat: 'DD, d MM, yy',
      beforeShowDay: noWeekendsOrHolidays,
      showOn: 'button',
      buttonImage: 'images/calendar.gif', 
      buttonImageOnly: true
     });
  });
});

Create a Database in sql and put you holiday dates in MM/DD/YYYY format as Varchar Put the below contents in a file getdate.php


[php]
$sql="SELECT dates FROM holidaydates";
$result = mysql_query($sql);
$chkdate = $_POST['chkdate'];
$str='';
while($row = mysql_fetch_array($result))
{
$str .=$row[0].'';
}
echo $str;
[/php]

Happy Coding !!!! :-)


You can use noWeekends function to disable the weekend selection

  $(function() {
     $( "#datepicker" ).datepicker({
     beforeShowDay: $.datepicker.noWeekends
     });
     });

$("#selector").datepicker({ beforeShowDay: highlightDays });

...

var dates = [new Date("1/1/2011"), new Date("1/2/2011")];

function highlightDays(date) {

    for (var i = 0; i < dates.length; i++) {
        if (date - dates[i] == 0) {
            return [true,'', 'TOOLTIP'];
        }
    }
    return [false];

}

These answers were very helpful. Thank you.

My contribution below adds an array where multiple days can return false (we're closed every Tuesday, Wednesday and Thursday). And I bundled the specific dates plus years and the no-weekends functions.

If you want weekends off, add [Saturday], [Sunday] to the closedDays array.

$(document).ready(function(){

    $("#datepicker").datepicker({
        beforeShowDay: nonWorkingDates,
        numberOfMonths: 1,
        minDate: '05/01/09',
        maxDate: '+2M',
        firstDay: 1
    });

    function nonWorkingDates(date){
        var day = date.getDay(), Sunday = 0, Monday = 1, Tuesday = 2, Wednesday = 3, Thursday = 4, Friday = 5, Saturday = 6;
        var closedDates = [[7, 29, 2009], [8, 25, 2010]];
        var closedDays = [[Monday], [Tuesday]];
        for (var i = 0; i < closedDays.length; i++) {
            if (day == closedDays[i][0]) {
                return [false];
            }

        }

        for (i = 0; i < closedDates.length; i++) {
            if (date.getMonth() == closedDates[i][0] - 1 &&
            date.getDate() == closedDates[i][1] &&
            date.getFullYear() == closedDates[i][2]) {
                return [false];
            }
        }

        return [true];
    }




});

For Saturday and Sunday You can do something like this

             $('#orderdate').datepicker({
                               daysOfWeekDisabled: [0,6]
                 });

You can use noWeekends function to disable the weekend selection

  $(function() {
     $( "#datepicker" ).datepicker({
     beforeShowDay: $.datepicker.noWeekends
     });
     });

The datepicker has this functionality built in!

$( "#datepicker" ).datepicker({
  beforeShowDay: $.datepicker.noWeekends
});

http://api.jqueryui.com/datepicker/#utility-noWeekends


These answers were very helpful. Thank you.

My contribution below adds an array where multiple days can return false (we're closed every Tuesday, Wednesday and Thursday). And I bundled the specific dates plus years and the no-weekends functions.

If you want weekends off, add [Saturday], [Sunday] to the closedDays array.

$(document).ready(function(){

    $("#datepicker").datepicker({
        beforeShowDay: nonWorkingDates,
        numberOfMonths: 1,
        minDate: '05/01/09',
        maxDate: '+2M',
        firstDay: 1
    });

    function nonWorkingDates(date){
        var day = date.getDay(), Sunday = 0, Monday = 1, Tuesday = 2, Wednesday = 3, Thursday = 4, Friday = 5, Saturday = 6;
        var closedDates = [[7, 29, 2009], [8, 25, 2010]];
        var closedDays = [[Monday], [Tuesday]];
        for (var i = 0; i < closedDays.length; i++) {
            if (day == closedDays[i][0]) {
                return [false];
            }

        }

        for (i = 0; i < closedDates.length; i++) {
            if (date.getMonth() == closedDates[i][0] - 1 &&
            date.getDate() == closedDates[i][1] &&
            date.getFullYear() == closedDates[i][2]) {
                return [false];
            }
        }

        return [true];
    }




});

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to jquery-ui

How to auto adjust the div size for all mobile / tablet display formats? jQuery not working with IE 11 JavaScript Uncaught ReferenceError: jQuery is not defined; Uncaught ReferenceError: $ is not defined Best Practice to Organize Javascript Library & CSS Folder Structure Change table header color using bootstrap How to get HTML 5 input type="date" working in Firefox and/or IE 10 Form Submit jQuery does not work Disable future dates after today in Jquery Ui Datepicker How to Set Active Tab in jQuery Ui How to use source: function()... and AJAX in JQuery UI autocomplete

Examples related to jquery-ui-datepicker

How to format date with hours, minutes and seconds when using jQuery UI Datepicker? Jquery UI datepicker. Disable array of Dates How to set minDate to current date in jQuery UI Datepicker? Jquery DatePicker Set default date jQuery UI: Datepicker set year range dropdown to 100 years How to add/subtract dates with JavaScript? setting min date in jquery datepicker How do I clear/reset the selected dates on the jQuery UI Datepicker calendar? jQuery Date Picker - disable past dates Getting value from JQUERY datepicker