Reputation: 33
I am pretty new to jquery and I want to add and delete table rows by clicking the add or remove image.
The adding button works perfectly and a manually added row with a delete button works perfectly, but if I add a new row and then click the delete button for the new row, it does nothing.
I have tried searching google and testing all the answers but none seem to work for me.
<script type="text/javascript">
$(document).ready(function(){
var idCount = 0;
idCount++;
var new_row="<tr><td><span style='float:left; margin-left:20px;'>IP: </span><input name='ipaddr' type='text' /></td><td><img src='images/delete.png' width='20px' height='20px' id='deleteRow' /></td></tr>";
$("table#ipList img#addRow").click(function() {
$("table#ipList").append(new_row);
});
$("table#ipList img#deleteRow").click(function() {
//$("img#deleteRow").parents("tr").remove();
//$("img#deleteRow").parent().parent().last().remove();
$("img#deleteRow").last().parent().parent().remove();
});
});
</script>
</head>
<body>
<table id="ipList">
<tr>
<td><span style="float:left; margin-left:20px;">IP: </span><input name="ipaddr" type="text" /></td>
<td><img src="images/add.png" width="20px" height="20px" id="addRow" /></td>
</tr>
<tr>
<td><span style="float:left; margin-left:20px;">IP: </span><input name="ipaddr" type="text" /></td>
<td><img src="images/delete.png" width="20px" height="20px" id="deleteRow" /></td>
</tr>
</table>
Upvotes: 0
Views: 5554
Reputation: 74420
Use delegation this way:
But IDs must be unique on context page!
$(document).ready(function () {
var idCount = 0;
idCount++;
$("#ipList").on('click', "#addRow", function () {
$("#ipList").append(new_row);
});
$("#ipList").on('click', "#deleteRow", function () {
$("#deleteRow").closest('tr').remove();
});
});
Upvotes: 4
Reputation: 1308
You're going to need event delegation. Use the on() method for this. http://api.jquery.com/on/
Upvotes: 1