Question

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

Was it helpful?

Solution 2

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.

OTHER TIPS

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");
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top