I'm trying to link the button across every row to delete that row when clicked. However, every delete button is linked to the onclick delete of the last created row.
For example:
TABLE
Record 1 | deleteButton1
Record 2 | deleteButton2
Record 3 | deleteButton3
Actions:
clicks deleteButton1 ---> deletes the row with "Record 3"
clicks deleteButton1 ---> tries to delete the row with "Record 3" (aka nothing happens b/c row not found)
clicks deleteButton2 ---> tries to delete the row with "Record 3" (aka nothing happens b/c row not found)
HTML:
<table id="Table"></table>
JavaScript:
//Code snippet
for (var x = 0; x < itemArray.length; x++)
{
selectedItem = itemArray[x];
table = document.getElementById("Table");
row = table.insertRow(table.rows.length);
cell1 = row.insertCell(0);
cell2 = row.insertCell(1);
cell1.innerHTML = selectedItem;
cell2.innerHTML = "<button>—</button>"; //Delete button across every row.
cell2.onclick = function () { removeRow(selectedItem); };
}
function removeRow(content, where)
{
var table;
table = document.getElementById("Table");
var iter;
for (var i = 0; i < table.rows.length; i++)
{
iter = table.rows[i].cells[0].innerHTML;
if (iter == content)
{
table.deleteRow(i);
}
}
}
You may need something like this :
Here :
for (var i= startingIndex; i< tbl.tBodies[0].rows.length; i++) {
// CONFIG: next line is affected by myRowObject settings
tbl.tBodies[0].rows[i].myRow.one.data = count; // text
// CONFIG: next line is affected by myRowObject settings
tbl.tBodies[0].rows[i].myRow.two.name = INPUT_NAME_FS; // input text
tbl.tBodies[0].rows[i].myRow.two.id = INPUT_NAME_FS + count;
tbl.tBodies[0].rows[i].myRow.three.name = INPUT_NAME_FS_DESIGN; // input text
tbl.tBodies[0].rows[i].myRow.three.id = INPUT_NAME_FS_DESIGN + count;
// CONFIG: next line is affected by myRowObj settings
// CONFIG: requires class named classy0 and classy1
tbl.tBodies[0].rows[i].className = 'classy' + (count % 2);
count++;
}
Each onclick
function references the variable selectedItem
. After your for
loop, that variable is set to the last item in the array. So, every button will reference that last item. Here is a demonstration .
I suggest using Javascript's parentNode
and rowIndex
to allow a button to reference its own parent row.
In my example below, rowIndex
returns the index number of the tr
that is the parentNode
for the clicked cell ( td
). This index number can be used to remove a table row directly.
cell2.onclick = function () { removeRow(this.parentNode.rowIndex); };
function removeRow(x) {
document.getElementById("Table").deleteRow(x);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.