jQuery UI datepicker highlighting dates

695 views Asked by At

I've tried to use this example for highlighting dates, unfortunately I use different versions of jQuery and jQuery UI and this doesn't work. The month which has highlighted days is not displayed. How do I fix this?

jQuery - v2.1.3

jQuery UI - v1.11.4

My code looks like this:

<div id="calendar"></div>

<script>
    jQuery(document).ready(function() {

        // An array of dates
        var eventDates = {};
        eventDates[ new Date( '07/07/2015' )] = new Date( '07/07/2015' );

        // datepicker
        jQuery('#calendar').datepicker({
            beforeShowDay: function( date ) {
                var highlight = eventDates[date];
                if( highlight ) {
                    return [true, "event", highlight];
                } else {
                    return [true, '', ''];
                }
            }
        });
    });
</script>
2

There are 2 answers

0
max890 On BEST ANSWER

This part of code can result in a weird behavior:

var eventDates = {};
eventDates[ new Date( '07/07/2015' )] = new Date( '07/07/2015' );

In that case, date will use his toString() method to return the key to use, but some object can just return [object Object].

This is why you should use always string for the key. Also, as you can see, you invoke twice the same date in your map array and this make your key useless in that case because key === value.

So instead maybe you want to use an array of string with toISOString:

var eventDates = [];
eventDates.push((new Date( '06/06/2015' )).toISOString(),
                (new Date( '06/07/2015' )).toISOString()
               );

Then you can use indexOf to check if the date is in your array:

return (eventDates.indexOf(date.toISOString()) > -1) ? [true, "event"] : [true, ""];

Here is the jsfiddle (thanks depperm for the template):

http://jsfiddle.net/ozud01wm/1/

2
depperm On

That is a good question. I changed the jquery version to 1.8.3 and the jquery ui to 1.9.2 and then it works. Here is an example.