I have a "DOM" list in MVC 4 using jQuery to add elements dynamically but at the moment of removing all the elements The table no longer allows me to add more elements, I have tried to use length and comparisons but it does not work.
Am probably missing something obvious but can't see what it is. Any ideas?
Example
Here is my table code
<div><a href="#" id="addNew"><img src="~/Images/splus.png" alt="Add Product" style="border:0"/></a></div>
<table id="dataTable" border="0" cellpadding="0" cellspacing="0">
<thead>
<tr>
<th></th>
<th></th>
<th>Product</th>
<th>Quantity</th>
<th></th>
</tr>
</thead>
<tbody>
@if (Model != null && Model.Count > 0)
{
int j = 0;
int index = 1;
foreach (var i in Model)
{
<tr>
<td>@index</td>
<td>@Html.HiddenFor(a => a[j].SEQ_NO, new { id = "nrow", Value = index })</td>
<td>@Html.DropDownList("PRODUCTS", "Select Product")</td>
<td>@Html.TextBoxFor(a => a[j].QUANTITY)</td>
<td>
<a href="#" id="remove" class="remove"><img src="~/Images/sminus.png" alt="Add Product" style="border:0"/></a>
</td>
</tr>
index += 1;
j++;
}
}
</tbody>
</table>
Here is my jQuery Code when i click on Add New
$("#addNew").click(function (e) {
e.preventDefault();
var last = $('#dataTable>tbody>tr:last');
if (last.length > 0) {
var name = last.children().find('input,select')[0].name;
var index = Number(name.replace(/[^0-9]/gi, '')) + 1;
var tr = ('<tr>' + last.html().replace(/[0-9]+__/gi, index + '__') + '</tr>').replace(/\[[0-9]+\]+[.]/gi, '[' + index + '].');
numberRows($('#dataTable tbody').append(tr));
}
});
UPDATE:
Add "REMOVE CODE"
$(document).on('click', '#remove', function (e) {
e.preventDefault();
$(this).parent().parent().remove();
numberRows($('#dataTable tbody'));
});
tr:last
to be deleted (hide the delete button ontr:first
) or b) store your row template elsewhere - on a hidden tr or on a different, hidden tabletable>tbody>tr:first>td>a.remove { display:none; }
table>tbody>tr:first { display:none; }