I'm trying to delete a row using a checkbox but it seems just returning an error TypeError: Cannot read property childNodes of undefined
function deleteRowFromTable(tableID) {
try {
var table = document.getElementById(tableID);
var rowCount = table.rows.length - 1;
alert(rowCount);
for (var i = 0; i < rowCount; i++) {
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
if (null != chkbox && true == chkbox.checked) {
table.deleteRow(i);
rowCount--;
i--;
}
}
} catch (e) {
alert(e);
}
}
function addRowToTable(tableID) {
var table = document.getElementById(tableID);
var jobValue = jobValue + 1; //increase personVal by 1
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
// var colCount = table.rows[0].cells.length;
//generate textbox here with dynamic id by adding jobVal at the end of id and '-'(dash) is used to split id later
var newcell = row.insertCell(0);
newcell.innerHTML = "<input type='checkbox' name='chk' />";
var newcell = row.insertCell(1);
newcell.innerHTML = "<input type='text' name='txtLineofBusiness-" + jobValue + "' id='txtLineofBusiness-" + jobValue + "' class='txtLineofBusiness' required/>";
var newcell = row.insertCell(2);
newcell.innerHTML = "<input type='text' name='txtNofUnits-" + jobValue + "' id='txtNofUnits-" + jobValue + "' class='txtNofUnits' required/>";
var newcell = row.insertCell(3);
newcell.innerHTML = "<input type='text' name='txtCapital-" + jobValue + "' id='txtCapital-" + jobValue + "' class='txtCapital' required/>";
var newcell = row.insertCell(4);
newcell.innerHTML = "<input type='text' name='txtEssential-" + jobValue + "' id='txtEssential-" + jobValue + "' class='txtEssential' required/>";
var newcell = row.insertCell(5);
newcell.innerHTML = "<input type='text' name='txtNonEssential-" + jobValue + "' id='txtNonEssential-" + jobValue + "' class='txtNonEssential' required/>";
}
<input type="button" value="Add Rows" onclick="addRowToTable('tableId')">
<input class="col-md-2" type="button" value="Delete Row/s" onclick="deleteRowFromTable('tableId')">
<table id="tableId">
<thead>
<tr>
<th rowspan=2>#</th>
<th rowspan=2>Line of Business</th>
<th rowspan=2>No. of Units</th>
<th rowspan=2>Capitalization</th>
<th colspan="2">Gross /Sales Receipts </th>
</tr>
<tr>
<th>Essential</th>
<th>Non-essential</th>
</tr>
</thead>
</table>
I don't have default table rows for them. I am trying to add some rows which is successful but the delete row doesn't work. Please help.
<th>in it, which does not have a checkbox.var newcellonly once. The rest of thenewcellis just a reference to the same variable (i.e. they are all identical.var X= 1, later onX=2... that doesn't make 2 separate X with the value of 1 and the other with a value of 2. It's justX=2. So does theaddRow()function work or did you copy and paste a much smaller function then copied the pattern with different content?