javascriptjquerypickadate

Pickadate.js dynamically changes disabled days


I'm using the Pickadate.js library on a checkout page for customers to select collection dates for ordered products.

In the back-end, the client is able to block off certain days so that the client cannot select this day. For eg. Sunday, since the store is closed on a Sunday.

I am initializing the the library like so:

/* Initiate the Datepicker */
        var $dateInput = $('#collection-date').pickadate({
            firstDay: 2,
            onSet: function(e) {
                if(e.select) {
                    $('#select-time').slideDown();
                    var timeInput = $('#collection-time').pickatime();
                } else {
                    $('#select-time').slideUp();
                }
            },
        });
        var picker = $dateInput.pickadate('picker');

On the checkout page, the customer can choose between 2 stores which have varying collection times so the calendar needs to be able to pick up which store is being selected and based on that, display available days for collection.

I set the disabled days like so:

function get_disabled_days(store_id) {

        var days_array = [];
        days_array = $('#store-' + store_id).find('.disabled-days').attr('data-disabled-dates').split(',').map(function(item) {
            return parseInt(item, 10);
        });

        //console.log(days_array);

        return days_array;

    }

Once store is selected I call:

picker.set('disable', get_disabled_days(store_id));

This function correctly returns the array of days (as integers) and blocks off the right days.

My problem comes in once a customer changes the store. Instead of resetting the disabled days array it simply adds on the disabled days of the selected store. So if a customer selects a second store, the calendar will block out the days for both the first selected store and then the second selected store.

I've tried to stop() the library and reinitialize it which doesn't work but I cannot figure out how to clear the disabled date array and re-set it once a customer selects a new store.


Solution

  • If I understand this correctly, you need to reset the dates in the datepicker so that when the new store has been selected, it only disables dates pertaining to that store.

    As the docs specify,

    An important thing to note here is that “setting” something as enabled or disabled adds the new elements to the collection of items to disable rather than completely replacing them with the new collection.

    So could you just enable all the dates before running the disable call?

    // Enable all the dates
    picker.set('enable', true)
    picker.set('disable', false)
    
    picker.set('disable', get_disabled_days(store_id));