Search code examples
javascriptjqueryjquery-uidatejquery-ui-datepicker

How to Disable the very next weekends in jQuery UI Datepicker?


In an order page I want to implement a calendar, in which, if the user is ordering on friday after 10am, then block the following saturday and sunday in delivery date calendar. Here is a sample code I am trying, but not working as intended.

beforeShowDay: function(date) {
    var day = dt.getDay();
    var hour = dt.getHours();
    if (day == 4) {
        // i think, here i want to put the code to disable days
    }
}

If I use something like this

beforeShowDay: function(date) {
    var day = date.getDay();
    var dt = new Date();
    var hour = dt.getHours();
    return [(day != 5 && day != 6)];
}

I am able to disable Sat and Sun days, but this will disable all the Sat and Sun days. I wnat to disable only the very next Sat n Sun days to be disabled. Also I can get current Hour in var hour, So where should I use the condition to check if the hour is greater than 10am, I am using something like this but not working

beforeShowDay: function(date) {
    var dt = new Date();
    var hour = dt.getHours();
    var day = date.getDay();
    if (day == 4 && hour >= 10) {
        return [(day != 5 && day != 6)];
    }
}

Solution

  • Inside the beforeShowDay function, check the current date to see if it is a Friday and after 10am. If this is true then you also need to check if the date passed as argument is the next Saturday or Sunday:

    $(function() {
      $("#datepicker").datepicker({
        beforeShowDay: function(date) {
          // date (Friday March 13 2015 10:00 AM) is hardcoded for testing
          var now = new Date(2015, 3 - 1, 13, 10, 0, 0, 0);
          if (now.getDay() === 5 && now.getHours() >= 10) {
            var now_plus_1 = new Date(now.getTime()); now_plus_1.setHours(0, 0, 0, 0); now_plus_1.setDate(now_plus_1.getDate() + 1);
            var now_plus_2 = new Date(now.getTime()); now_plus_2.setHours(0, 0, 0, 0); now_plus_2.setDate(now_plus_2.getDate() + 2);
            return [date.getTime() !== now_plus_1.getTime() && date.getTime() !== now_plus_2.getTime(), ""];
          }
          return [true, ""];
        }
      });
    });
    @import url("//ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/ui-darkness/jquery-ui.min.css");
    
    body { font-size: smaller; }
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
    
    <input id="datepicker">