SachaDee SachaDee - 25 days ago 7
Javascript Question

How to get click event on a new created row with Jquery

I have a

table
:

<table id="myTable" style="cursor :pointer;">
<tr>
<td>col 1</td><td>col2</td>
</tr>
<tr>
<td>field</td><td>Field 2</td>
</tr>
<tr>
<td>another field</td><td>one more field</td>
</tr>
</table>


when I click on a
row
this code add a new
row
:

$("#myTable tr").click(function(){
$(this).addClass('selected').siblings().removeClass('selected');
var value=$(this).find('td:eq(1)').html();
if (value) {
alert('adding New Row !')
$('#myTable').find('tbody:last').append('<tr><td>new Field</td><td>New Field</td></tr>');
}
});


JSFiddle Demo

But now when I click on the new created
row
nothing append.
Why another
row
is not created ?

Is there a way to do that ?

Answer

Use event delegation instead:

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