I’m reading this link:
append a row to a table and increment a value with javascript
and I like as it is but I wanted to add a remove button on each row.
I was able to put the add button on each row, but how to remove the row when I click on the "remove" button?
Here is what I tried:
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var lastRow = table.rows[rowCount - 1];
var lastRowValue = parseInt(lastRow.cells[0].children[0].value);
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
for (var i = 0; i < colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[0].cells[i].innerHTML;
}
// Increment value of Segment by 1
row.cells[0].children[0].value = lastRowValue + 1;
}
<table>
<thead>
<th>#</th>
<th>item1</th>
<th>item2</th>
<th></th>
</tr>
</thead>
<tbody id="dataTable" class="table">
<tr>
<td><input type="text" value="1" name="chk[]"></td>
<td><input type="text" value="1" name="chk[]"></td>
<td><input type="button" value="add" onClick="addRow('dataTable')" /> | <input type="button" value="delete" /></td>
</tr>
</tbody>
</table>
Specifically what I’m not able to do is refresh the item value on the first input field when I click the remove button… and of course delete the row when I click on the remove button
2
Answers
Like this
Note I do not need to keep track of number of rows and I delegate the click
Also I fixed your invalid HTML
Update Your Code Like This add a onClick JavScript Function to delete Rows