I found a strange bug while testing the remove function on my tables. When building an HTML Form. Lets say there are 5 rows.
When I delete row 3 there are now 4 rows visible to the user. In the when I console.log(#partTable tr).length the table has 4 rows.
When I console.log the contents of the table I see rows 1, 2, 4, and 5. But when the viewModel gets the table, as part of the post action, the viewModel will only contain 1 and 2.
That missing row must break the code of the table when it gets submitted and ends the table rows where there is a form of null in the middle. Here is my code.
First is the code for adding rows to the table followed by the function that removes a row from that table.
$("body").on("click", "#btnAdd", function () {
//Reference
var counter = $("#tblPart tr").length - 1;
var txtName = $(`#patz${counter}`);
var quant = $(`#quantz${counter}`);
// Build
var first = `<tr> <td class="rowIndex"> <input name='PartNumberModel[${counter}].SubPartNumber' type = 'text' required = "required" /></td> `;
var third = `<td><input name= 'PartNumberModel[${counter}].SubQuantity' type= 'number', min='0' /></td>`;
var removeButton = "<td><input type= 'button', onclick='Remove(this)', value = 'Remove' /></td> </tr>";
////Add Row.
var markup = first + third + removeButton;
$("#tblPart tbody").append(markup);
console.log(markup);
});
function Remove(button) {
//Determine the reference of the Row using the Button.
var row = $(button).closest("TR");
var name = $("TD", row).eq(0).html();
if (confirm("Do you want to delete: " + name)) {
//Get the reference of the Table.
var table = $("#tblPart")[0];
//Delete the Table row using it's Index.
table.deleteRow(row[0].rowIndex);
}
};
Here is the code for the HTML portion of the table that gets the rows added to it.
<div class="row justify-content-center">
<div class="form-group col-md-6">
<input type="button" value="Add" class="button is-primary" id="btnAdd" />
<table id="tblPart" style="table-layout:fixed; width:100%;">
<thead>
<tr>
<th>
Part Number
</th>
<th>
Quantity
</th>
<th>
Remove Row
</th>
</tr>
</thead>
<tbody>
@for (var i = 0; i < Model.PartNumberModel.Count(); i++)
{
<tr>
<td>
@Html.TextBoxFor(modelItem => Model.PartNumberModel[i].SubPartNumber, new { id = $"patz{i}", required = "required" })
</td>
<td>
@Html.TextBoxFor(modelItem => Model.PartNumberModel[i].SubQuantity, new { type = "number", min = "0", id = $"quantz{i}", required = "required" })
</td>
<td>
<input type='button' onclick='Remove(this)' value='Remove' />
</td>
</tr>
}
</tbody>
</table>
</div>
</div>
Thank you for any help you’re able to offer.