jquery - Can't delete dynamically added table row -
i pretty new jquery , want add , delete table rows clicking add or remove image.
the adding button works , manually added row delete button works perfectly, if add new row , click delete button new row, nothing.
i have tried searching google , testing answers none seem work 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>
use delegation way:
but ids must 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(); }); });
Comments
Post a Comment