Search code examples
javascriptjquerybootstrap-datepicker

setDateDisabled + start/end date break bootstrap-datepicker


I'm using the bootstrap-datepicker from eternicode and I'm against a strange behaviour.

When I try to use the setDatesDisabled option on the fly with the default startDate and endDate option, the datepicker seem to freez and don't allow me to change the month any-more.

The strangest thing is a simple alert() just before the call of setDatesDisabled seem to correct the bug...

My final need is to add some disabledDate on the fly, using a function as a data provider

The simplified code :

        // enable the datepicker on fields
    $('.date-picker').datepicker({
            format: 'yyyy-mm-dd',
            startDate: '2016-04-01',
            endDate: '2016-08-15',
            datesDisabled: ['2016-04-21','2016-04-20','2016-04-13']
        })
        .on('show', function(ev){
            // @TODO check why bug here...
        // alert('hi'); // uncomment to patch bug
            $(this).datepicker('setDatesDisabled', ['2016-04-17','2016-04-16']);

        });

Check the JSFiddle to reproduce.

Does anyone face the same thing / have a work around to disable some date on the fly ?

I've already make a bug report on the eternicode Github, as I think is may be an internal bug.


Solution

  • Its most likely due to the fact that the datepicker 'show' event fires multiple times as you navigate while the datepicker calendar is open.

    Setting disabled dates while the callendar is already opened causes it to be recalculated and reloaded so it navigates back to the month with the currently selected date - this makes it impossible to navigate away from the page with the selected date (the half working scenario happens when there is no selected date).

    Not sure if this is applicable in your scenario but this should work when you set the disabled dates only when calendar is not opened.

    I changed

    .on('show', function(ev){
    

    to

    $('.date-picker').on('click', function(ev){
    

    and this seemed to work fine, see the updated fiddle:

    https://jsfiddle.net/zj9sjspf/11/

    Second slightly "hackish" solution is that you could disable automatic showOnFocus, and manually check if the calendar is not opened + set the new disabled dates + trigger show manually when the field is being focused on. This is not the best way of doing this, but might be the way to go while you wait on replies on your bug report ;)

    One way of doing this can be seen here: https://jsfiddle.net/zj9sjspf/13/