Question

I am an apprentice and new to programming, I know very little J-Query, JavaScript etc. I am creating a program where users will book days using a datepicker. I want all UK Bank Holidays to be disabled in the datepicker. I have a JSON file from the government website which has all the days that I would like to be disabled and other data. I want them to be disabled like the weekend that are currently disabled in the datepicker.

function IsWeekend(date) {
if (date.getDay() === 0 || date.getDay() === 6) return true;
else return false;
}

$(function () {
    $(".datepicker").datepicker({
        minDate: ('+1d'),
        dateFormat: 'dd/mm/yy',
        beforeShowDay: function (date) {
            return [(!IsWeekend(date))];
        }
    });
});

The JSON file is in this format

{"england-and-wales":{"division":"england-and-wales","events":[{"title":"New Year\u2019s Day","date":"2012-01-02","notes":"Substitute day","bunting":true},
{"title":"Good Friday","date":"2012-04-06","notes":"","bunting":false}
Was it helpful?

Solution

The solution is that we will first need to read the json file and load it to extract the dates to disable.

As AJAX calls can't be made remotely due to same origin policy you will have to copy the contents into a local JSON file.

Then we will traverse over the england-and-wales index as we are only concerned with the dates here and create an array and just have an additional check that if its a weekend or a date is present in this array we will disable it.

So the JavaScript code will be something .

var holidayDates = new Array(); // this array will store the holiday dates after being extracted form the JSON
     $.ajax({
       url: 'json/bank-holiday.json',// change the link to your local copy
       method: 'GET',
       dataType: 'json',
       success: function(data) {
         // now the data is loaded and we will traverse over the "england-and-wale" 's events and create an array to of dates of holidays
         var listOfEvents = data['england-and-wales'].events;
         for (var i in listOfEvents) {
           holidayDates.push(listOfEvents[i].date);// push the date to our array for checking afterwards
         }

       }
     });

     function IsWeekend(date) {
       if (date.getDay() === 0 || date.getDay() === 6) return true;
       else return false;
     }

      $(function() {
       $(".datepicker").datepicker({
         minDate: ('+1d'),
         dateFormat: 'dd/mm/yy',
         beforeShowDay: function(date) {
           var string = jQuery.datepicker.formatDate('yy-mm-dd', date);
           var isDisabled = (!IsWeekend(date)) && (holidayDates.indexOf(string) == -1); // used to disable if its an holiday or weekend
           return [isDisabled];
         }
       });
     });

I have also created a working sample that you can find here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top