Reputation: 722
I'm using jquery to add new row as well as delete row. The adding part works, but the delete doesn't work at all, and I can't figure out why. It would work the first time, and the rest of the time it just doesn't work. Specifically, the only time it would work is when I click the delete on the first row.
HTML
<table class="table table-striped table-bordered" id="entryTable">
<thead> ...
</thead>
<tbody>
<tr>
<td>...</td>
<td>...</td>
<td>...</td>
<td><a href="#" id="addRow">Add</a><br>
<a href="#" id="deleteRow">Delete</a>
</td>
</tr>
</tbody>
</table>
Jquery
var i = 1;
$("#addRow").click(function(){
$("table tr:last").clone().find("input, select, textarea").each(function(){
$(this).val('').attr({
'id': function(_,id){ return id+i},
'name': function(_,name){ return name+i},
'value':''
});
}).end().appendTo("table");
i++;
});
$("#deleteRow").click(function(){
alert("delete clicked")
$(this).parent().parent().remove();
});
I've tried changing $(this).parent().parent().remove();
to $(this).closest("tr").remove();
but that doesn't work as well.
I've also tried doing it like <a href="#" onclick="deleteRow(this)">
and declaring a function deleteRow but that hasn't helped either.
Would definitely appreciate help or pointers here. Thank you.
Upvotes: 0
Views: 1247
Reputation:
Try this:
$(function () {
$(document).on('click', '#deleteRow', function(e){
$(this).closest('tr').remove();
e.stopPropagation();
});
});
Upvotes: 0
Reputation: 5211
$(document).on('click', '#deleteRow', function(){
alert("delete clicked")
$(this).parent().parent().remove();
});
Use event delegation method for dynamically created elements.
Demo:
Upvotes: 5