Question

I try to use datepicker to show a busy/free calendar. I use beforeShowDay to switch between two classes, but it doesn't work. The last day apply the class for all dates.

var SelectedDates = {};
 SelectedDates['2014-05-04'] = true;
 SelectedDates['2014-05-03'] = true;
 SelectedDates['2014-05-02'] = true;

    $(function() {
        $("#datepicker").datepicker({
            numberOfMonths: 3,
            showCurrentAtPos: 1,
            beforeShowDay: function (date) {
                var dateFormatted = date.getFullYear() +
                    "-" + (date.getMonth() < 10 ? "0" + date.getMonth() : date.getMonth()) +
                    "-" + (date.getDate() < 10 ? "0" + date.getDate() : date.getDate());

                console.log("date js: " + dateFormatted + " highlight: " + SelectedDates[dateFormatted]);
                var highlight = SelectedDates[dateFormatted];

                if (highlight === true) {
                    console.log("add busy class to " + dateFormatted);
                    return [false, 'Busy'];
                }
                console.log("add free class to " + dateFormatted);
                return [true, 'Free'];
            }
        });

    });

Here's the fiddle : http://jsfiddle.net/b22Bz/

Thanks,

Was it helpful?

Solution

Months are 0 based in Javascript (0=January, 1=February etc), so when getMonth() is called on the date 2014-05-04, it will return 4 not 5.

I've modified the line of code where you set dateFormatted from:

var dateFormatted = date.getFullYear() +
                "-" + (date.getMonth() < 10 ? "0" + date.getMonth() : date.getMonth()) +
                "-" + (date.getDate() < 10 ? "0" + date.getDate() : date.getDate());

to:

var dateFormatted = date.getFullYear() +
                    "-" + (date.getMonth() < 10 ? "0" + (date.getMonth()+1) : (date.getMonth()+1)) +
                    "-" + (date.getDate() < 10 ? "0" + date.getDate() : date.getDate());

See an updated Fiddle here

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