0

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,

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Yeah! Many thanks, your explications are just perfect!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.