DeleteRow Sometimes Deletes The Right Row And Sometimes Not In Javascript
I have a table. At the end of each row tehere is a href 'X' which deletes this row. This is pretty simple. Now when you click 'X' for any row 2 it deletes row 2, but then when you
Solution 1:
You have hard-coded the row numbers, so after the first deletion they are out of sync. The <table>
element's .rows
property is "live", so removing one means the numbers no longer line up with your HTML.
Instead, consider passing this.parentNode.parentNode
to the function and using it to determine which row to delete:
<a title="my title text" id="6" href="#" class="someclass" onclick="deleteRows(this.parentNode.parentNode)">X</a>
Then use removeChild()
in the function:
function deleteRows(row) {
var tbl = document.getElementById('my_table'); // table reference
tbl.getElementsByTagName("tbody")[0].removeChild(row);
}
Edit: The <tr>
is a child of the <tbody>
element, so that must be the parent from which it is removed.
If you would really rather do it with deleteRow()
, then loop through the rows to find the one passed to the function and delete it:
function deleteRows(row) {
var tbl = document.getElementById('my_table'); // table reference
// Loop over the table .rows collection to find the one passed into the function
for (var i=0; i<tbl.rows.length; i++) {
if (row == tbl.rows[i]) {
// And delete it
tbl.deleteRow(i);
return;
}
}
}
Solution 2:
Why not do something like this? Using jQuery isn't hard to add into existing files/sites.
HTML:
<table id="my_table" cellspacing="0" cellpadding="0">
<tr>
<td>Custom0</td>
<td><span title="my title text" id="1" class="someclass">X</span></td>
</tr>
<tr>
<td>Custom1</td>
<td><span title="my title text" id="2" class="someclass">X</span></td>
</tr>
</table>
JavaScript:
$('.someclass').on('click', function() {
$(this).parent().parent().remove();
});
Post a Comment for "DeleteRow Sometimes Deletes The Right Row And Sometimes Not In Javascript"