-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
  • 29,389
  • 8
  • 76
  • 90
Saurabh Kumar
  • 15,763
  • 47
  • 125
  • 205

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,270
  • 4
  • 26
  • 45
0

I think you want to use delegate instead.

Mike Thomsen
  • 35,490
  • 10
  • 55
  • 80
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,828
  • 1
  • 29
  • 46
-2

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

Johni
  • 2,822
  • 4
  • 24
  • 47