I need to detect click events on rows that are added dynamically to a table (using jQuery). The table has the id myTable
.
This is no problem for table rows created at design time/hard coded to the local page; I know I can use $('#myTable tr').click(...);
However, my use case is loading new table rows via ajax and appending it to the table. In this situation, the click event handler is not called.
In the past I used jQuery’s .live()
function for handling dynamically loaded elements, but I see that has been deprecated now in favour of .on()
. This would be fine, except that it is not working for me in this situation.
Here is some demonstration code and a jsfiddle that shows the issue. Notice that clicking on ‘Static row’ displays an alert box, as intended, yet this does not happen for the dynamically added rows:
<!DOCTYPE html>
<body>
<h1>Dynamic table event test</h1>
<table id="myTable">
<tr><td>Static row</td></tr>
</table>
<button onclick="addTableRow()">Add row</button>
<script>
function addTableRow() {
$('#myTable').append('<tr><td>Dynamic row</td></tr>');
}
$('#myTable tr').on('click', function() {
alert('Row clicked');
});
</script>
</body>
</html>
3
Answers
Change
to
The first creates only eventhandelrs for elements matching your selector and attaching it to those elements that are present during load. The second attaches the handler to the parent table instead.
Since a new element (
tr
in your case) is added after the DOM-tree is loaded, that element is actually considered absent (as DOM-element), and so event is not being triggered.Yet, when you bind event to the parent element (that has been present before and after appending of new/alien element to the DOM) with targeting on any of its desired/potential children (i.e.
tr
), – the wanted action shall be achieved.Event-delegation approach
Try this:
You need to use the inside selector to attach events to dynamically created elements. Because this method attach the event to the parent, that already exists.