Skip to content
Advertisement

JQUERY DATEPICKER – exclude Sundays, specific dates AND disable next day selection after 12pm

I’m hoping someone here can help me with the following: –

Currently, I have the following script for my datepicker snippet where I have excluded Sundays.

  <script>
window.onload = function() {
  if (window.jQuery) {
    let $ = window.jQuery;

    $(function() {
      $("#date").datepicker({
        dateFormat: 'dd/mm/yy',
        minDate: +1, 
        maxDate: '+2M',
        beforeShowDay: function(date) {
    var day = date.getDay();
    return [(day != 0), ''];
        }
      });
    });
  }
}

I would like to add the following conditions: –

  1. Exclude multiple specific dates (i.e. 16/04/21, etc.)
  2. Disable next business day selection by customers AFTER 12pm.

For point #2, I have the following code but am unsure of where to include it in the above: –

$("#date" ).datepicker({  
minDate: +1,
beforeShow : function(){
    var dateTime = new Date();
    var hour = dateTime.getHours();
    if(hour  >= 12){
        $(this).datepicker( "option", "minDate", "+2" );
     }
 }

Please let me know, thank you!

Advertisement

Answer

Please refer below code snippet:

$(function () {
    // Dates to exclude
    var excludeDays = ['2021-04-15', '2021-04-16', '2021-04-30'];
    function disableSpecificDate(date) {
        // To disable specific day
        var dateArr = [String(date.getFullYear()), String(date.getMonth() + 1), String(date.getDate())];
        if (dateArr[1].length == 1) dateArr[1] = "0" + dateArr[1];
        if (dateArr[2].length == 1) dateArr[2] = "0" + dateArr[2];
        return excludeDays.indexOf(dateArr.join("-")) == -1;
    }
    $("#date").datepicker({
        dateFormat: 'dd/mm/yy',
        minDate: +1,
        maxDate: '+2M',
        beforeShow: function () {
            // To exclude next business day after 12 PM
            if (new Date().getHours() >= 12) {
                $(this).datepicker("option", "minDate", +2);
            }
        },
        beforeShowDay: function (date) {
            var day = date.getDay();
            return [(day == 0 ? false : disableSpecificDate(date)), ''];
        }
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js" integrity="sha512-uto9mlQzrs59VwILcLiRYeLKPPbS/bT71da/OEBYEwcdNUk8jYIy+D176RYoop1Da+f9mvkYrmj5MCLZWEtQuA==" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css" integrity="sha512-aOG0c6nPNzGk+5zjwyJaoRUgCdOrfSDhmMID2u4+OIslr0GjpLKo7Xm0Ao3xmpM4T8AmIouRkqwj1nrdVsLKEQ==" crossorigin="anonymous" />
<input id="date"/>
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement