Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery click function not working after removing and adding back elements

this is my click function

$('.cal table tbody td').on('click', function () {
    if($(this).hasClass('available'))
    {
        alert('asd');
    }
});

the problem i am having is that after i have switched to the next or previous month, my clicking function on the calendar does not work.

For example in my JSFIDDLE, if u move to the previous month and then move back to the current month and do the click function, it wouldn't work anymore.

EDIT: I'm using an external library called date.js, check out my jsfiddle for a clearer idea of what is going on.

EDIT 2: updated jsfiddle link

jsfiddle

like image 483
abcd1234123123 Avatar asked Feb 03 '26 01:02

abcd1234123123


2 Answers

Use this

$(document).on('click','.cal table tbody td', function () {
        if ($(this).hasClass('available')) {
            alert('asd');
        }
});

instead of this

$('.cal table tbody td').on('click', function () {
        if ($(this).hasClass('available')) {
            alert('asd');
        }
    });

Former is the correct replacement for delegate

like image 84
Anupam Avatar answered Feb 05 '26 19:02

Anupam


one thing I notice immediately is that when you do things like:

$('#calendar tbody').append('<tr id = row'+i+'></tr>'); 

you need to remember that when you want to give an ID to an element the 'value' portion of the ID should be enclosed in quotations.

So you need to escape the string to include them so your browser can interpret the html properly.

ie

$('#calendar tbody').append('<tr id = \"row'+i+'\"></tr>');

that way your output looks like:

<tr id="rowx"></tr>

instead of:

<tr id=rowx></tr>
like image 24
uofc Avatar answered Feb 05 '26 18:02

uofc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!