In each function DeleteRow(tableId,Index) you pass the table identifier and a static index, so document.getElementById("mytable").deleteRow(Index) first find the node table, then find no tr elements as children and do not assign an index element tr element start from 0 and do not delete the corresponding index tr.
Whenever you delete the first row, it will correspond to index 0 of 3 elements and delete the first row. Now there are 2 three left with index 0 and 1, dynamically assigned according to the table, but you are trying to match with 1 and 2.
to delete the second line, it will remove tr with index 1 (third tr), not the second tr.
to delete the actual index of the third row - 0 (after deleting 2 rows), and you go through 1, because for this reason it will not find the corresponding index.
Here is a simple javascript solution.
<script> function delRow(currElement) { var parentRowIndex = currElement.parentNode.parentNode.rowIndex; document.getElementById("myTable").deleteRow(parentRowIndex); } </script>
and html
<table id="myTable" style="border: 1px solid black"> <tr> <td><input type="text" id="fname"></td> <td><input type="button" value="Delete" onclick="delRow(this)"></td> </tr> <tr> <td><input type="text" id="fname"></td> <td><input type="button" value="Delete" onclick="delRow(this)"></td> </tr> <tr> <td><input type="text" id="fname"></td> <td><input type="button" value="Delete" onclick="delRow(this)"></td> </tr> </table>
here jsfiddle exmple
Press here
source share