-2

I am dynamically adding a table row (tr) to my table and these tr tags contain some links.

I have a jQuery script which is invoked when the links inside the tr are clicked. The script is not working for these links. It works when I reload the page and the tr is populated from the server side.

How can I overcome this problem?

$(".comment-like").on('click',function() {
    var spanEle = $(this).closest('li').find('.comment-like-count');
    if (spanEle.length) {
        var newCount = parseInt(spanEle.text(),10);
        spanEle.text(newCount + 1);
    }
});
Simon
  • 31,675
  • 9
  • 80
  • 92
Saurabh Kumar
  • 16,353
  • 49
  • 133
  • 212

4 Answers4

3

You should delegate the listener to a parent like the table not the links themselves since they come and go dynamically Try this:

$('your table selector').on('click','.comment-like', function () {
    var spanEle = $(this).closest('li').find('.comment-like-count');
    if (spanEle.length) {
        var newCount = parseInt(spanEle.text(), 10);
        spanEle.text(newCount + 1);
    }
});
kidwon
  • 4,448
  • 5
  • 28
  • 45
0

I think you want to use delegate instead.

Mike Thomsen
  • 36,828
  • 10
  • 60
  • 83
0

Choose a parent selector that exists on page load. If you don't have one, use $('body')

$('.elem-existing-on-pageload').on('click', '.comment-like', function() {
    ...
});
iappwebdev
  • 5,880
  • 1
  • 30
  • 47
-2

You have to attach the event handler for those new Elements after adding them.

Johni
  • 2,933
  • 4
  • 28
  • 47