0

In html there is <div id="tableContainer">and to it I appended dynamically created a table

table = $("<table id="myTable" class='helpTable'>");
table.append("<tr id='1'><td>content<td></tr>");code
table.append("<tr id='2'><td>content<td></tr>"); code
$('#tableContainer').append(table);

Now I want to add event on table row like

 $("#myTable tr").on('click',function(event) {
alert("Hi"); });

Its not working, however following is case is working

$("#tableContainer").on('click',function(event) {
alert("Hi"); });

i.e. I can have event on static html tag

Sandy
  • 142
  • 8

2 Answers2

2

You need to use event delegation as the table and the tr elements are created dynamically

$("#tableContainer").on('click', '#myTable tr', function (event) {
    alert("Hi");
});
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
  • Thanks Arun, actually `'click','#myTable tr'` didn't worked, but `'click','tr'` is working – Sandy Feb 08 '14 at 08:52
1

Here is final solution using delegation

$("#tableContainer").on('click', 'tr', function (event) { alert("Hi");});

Its delegation from parent element to child.

Jquery is shorthand for Javascript, delegation for dynamic elements is not looking shorthand.

Sandy
  • 142
  • 8