Gabriel Ciprian Magda
Gabriel Ciprian Magda

Reputation: 49

jquery datepicker UI on select event

I am using jquery ui datepicker to setup a calendar of events. I've created a string to give a class "dayWithEvents" to some dates in the calendar and what I want to do is when you click on one of these dates something to happen and something else when you click on days without this classs. So I give a specific class to some dates like this:

var eventsString = [
        '11/17/2014',
        '11/18/2014',
        '11/2/2014'
    ];
function highlightDays(date) {
    for (var i = 0; i < eventsString.length; i++) {
        if (new Date(eventsString[i]).toString() == date.toString()) {
            return [true, 'dayWithEvents'];
        }
    }
    return [true, ''];
}

And then I try to trigger the event when you click on one of those dates:

$('.ui-datepicker-calendar tbody tr td').click(function(){
        if($(this).hasClass('dayWithEvents')){
            alert('day with event');
        }
    });

The problem is that this work only the first time I click on one of the days that have this class. If I click it a second time, it won't work and also if I fist click another date and then one of the dates with this class it won't work.

You can see this calendar here: http://bootstrap.expert/tmp/cal/

Any ideea how to make it work everytime I click on these dates? Thanks

Upvotes: 1

Views: 1042

Answers (2)

Avishek
Avishek

Reputation: 1896

You need to declare the event handler each time the calender DOM reloads. If there is any callback event available for the calendar, declare the click event inside the callback.

Or, you can re-initiate the event on each click.

function eventInit(){
    $('.ui-datepicker-calendar tbody tr td').click(function(){
        if($(this).hasClass('dayWithEvents')){
            alert('day with event');
            eventInit();
        }
    });
}
eventInit();

Upvotes: 1

Mivaweb
Mivaweb

Reputation: 5732

Change you js code into this:

Use the .on() event handler to dynamically add the click event to all your table cells that has the class dayWithEvents

$('.ui-datepicker-calendar').on('click', 'tbody tr td.dayWithEvents', function(){
    alert('day with event');
});

Upvotes: 0

Related Questions