Home > OS >  Disable weekends and specific dates jQueryUI datepicker
Disable weekends and specific dates jQueryUI datepicker

Time:11-30

I want to disable weekends in the datepicker, as well as specific dates which will be in an array. I've noticed I cannot combine these 2 options in beforeShowDay as it only accepts 1 function. Is there a way I can add 2 function in beforeShowDay?

$(function() {
  var unavailableDates = ["27-12-2021", "28-12-2021", "29-12-2021", "30-12-2021", "31-12-2021", "01-01-2022", "02-01-2022", "03-01-2022", "04-01-2022"];

  function unavailable(date) {
    dmy = date.getDate()   "-"   (date.getMonth()   1)   "-"   date.getFullYear();
    if ($.inArray(dmy, unavailableDates) == -1) {
      return [true, ""];
    } else {
      return [false, "", "Unavailable"];
    }
  }

  $("#datepicker").datepicker({
    dateFormat: "dd-mm-yy",
    changeMonth: false,
    changeYear: false,
    minDate: '10D',
    beforeShowDay: $.datepicker.noWeekends, unavailable // throws an error becaus ei have 2 options
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.13.0/jquery-ui.min.js"></script>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" />
<input type="text" id="datepicker" />
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

The issue is because the beforeShowDay property only accepts a single function.

To do what you require you can create an anonymous function where you call both noWeekends() and your unavailable() functions and combine the result, like this:

jQuery($ => {
  let unavailableDates = ["27-12-2021", "28-12-2021", "29-12-2021", "30-12-2021", "31-12-2021", "01-01-2022", "02-01-2022", "03-01-2022", "04-01-2022"];

  let unavailable = date => $.inArray(`${date.getDate()}-${(date.getMonth()   1)}-${date.getFullYear()}`, unavailableDates) == -1;

  $("#datepicker").datepicker({
    dateFormat: "dd-mm-yy",
    changeMonth: false,
    changeYear: false,
    minDate: '10D',
    beforeShowDay: date => {
      if (!unavailable(date) || !$.datepicker.noWeekends(date)[0]) {
        return [false, "", "Unavailable"];
      } else {
        return [true, ""];
      }
    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.13.0/jquery-ui.min.js"></script>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" />
<input type="text" id="datepicker" />
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related