Reputation: 2350
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>
Upvotes: 1
Views: 146
Reputation: 416
$('#myTable').on('click', 'tr', function() {
alert('Row clicked');
});
Since new element (tr
in your case) is added after the DOM-tree is loaded, that element is considered absent (as DOM-element), and so the event is not being triggered.
Yet, when you bind event to the parent element (that has initially been present in DOM-tree), and target on any of its children (i.e. tr
), - the wanted action shall be achieved.
Upvotes: 1
Reputation: 130
Try this:
$('#myTable').on('click', 'tr', function() {
alert('something');
});
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.
Upvotes: 1
Reputation: 1721
Change
$('#myTable tr').click(...);
to
$('#myTable').on('click', 'tr', function() { ... });
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.
Upvotes: 1