19

I have an empty table to which I'm adding rows via jQuery using:

$('#table > tbody:last').append('<tr id="' + symbol.Code1 + '"><td>' + symbol.Code1 + '</td><td>' + symbol.Code2+ '</td><td>' + symbol.Code3+ '</td></tr>');

Everything is OK but when I implement:

$("#table tr").click(function(e) {
    alert(this.id);
});

nothing happens.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
user1770849
  • 193
  • 1
  • 1
  • 5

4 Answers4

38

You need event delegation you can use on to bind the click event for dynamically added elements. The way you are binding with click will apply on existing element but not elements which are added later.

$(document).on("click", "#table tr", function(e) {
    alert(this.id);
});

You can limit the scope for on by giving closest parent selector either by id or by class of parent.

$('.ParentElementClass').on("click", "#table tr", function(e) {
    alert(this.id);
});

Delegated events

Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers.

Adil
  • 146,340
  • 25
  • 209
  • 204
  • 3
    FWIW, I wouldn't recommend to use `document` or `body` as the parent selector, since it makes event reaction slower. It is better to use the closest static parent. – VisioN Oct 24 '12 at 10:39
  • 1
    Thanks for the answer. I spent hrs scratching my head about similar problem – binshi Sep 07 '16 at 09:12
  • FINALLY, someone answered the question I was looking for. I had exactly the same issue. – CashCow Feb 14 '17 at 13:02
10

You have to use the .on method

$("#table").on('click','tr',function(e) { 
    alert($(this).attr('id')); 
}); 
Mihai Matei
  • 24,166
  • 5
  • 32
  • 50
  • I think this is a better answer than the accepted one as it locks to the closest *static* parent as @VisioN has mentioned. – SharpC Oct 01 '17 at 17:09
2

You add rows dynamically after you have bound the event to the existing ones. You may use delegated event approach to fix the problem:

$("#table").on("click", "tr", function(e) {
    alert(this.id);
});
VisioN
  • 143,310
  • 32
  • 282
  • 281
1
$(document).on('click', "#tbl-body tr td", function(e) { 
    alert(this.id);
});
  • 2
    Whilst this code snippet is welcome, and may provide some help, it would be [greatly improved if it included an explanation](//meta.stackexchange.com/q/114762) of *how* it addresses the question. Without that, your answer has much less educational value - remember that you are answering the question for readers in the future, not just the person asking now! Please [edit] your answer to add explanation, and give an indication of what limitations and assumptions apply. – Toby Speight May 01 '17 at 12:05