I have a problem with REMOVE
, I currently have a dynamic table with which I add more rows and also add a link called REMOVE
which should remove the row, but currently I'm not performing the function of removing, insert the row if it works perfectly.
My code JavaScript
is as follows:
<script language="javascript">
$(document).ready(function () {
//1. Add new row
$("#addNew").click(function (e) {
e.preventDefault();
var $tableBody = $("#objetivos");
var $trLast = $tableBody.find("tr:last");
var $trNew = $trLast.clone();
var suffix = $trNew.find(':input:first').attr('name').match(/\d+/);
$trNew.find("td:last").html('<a href="#" id="removecell">Remove</a>');
$.each($trNew.find(':input'), function (i, val) {
// Replaced Name
var oldN = $(this).attr('name');
var newN = oldN.replace('[' + suffix + ']', '[' + (parseInt(suffix) + 1) + ']');
$(this).attr('name', newN);
//Replaced value
var type = $(this).attr('type');
if (type.toLowerCase() == "text") {
$(this).attr('value', '');
}
// If you have another Type then replace with default value
$(this).removeClass("input-validation-error");
});
$trLast.after($trNew);
// Re-assign Validation
var form = $("form")
.removeData("validator")
.removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse(form);
});
// 2. Remove
$('#removecell').live("click", function (e) {
e.preventDefault();
$(this).parent().parent().remove();
});
});
</script>
My view is as follows:
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<br /><br />
<div><a class="btn btn-info" href="#" id="addNew">+</a></div>
<br />
<table id="objetivos" class="table table-bordered table-hover">
<tr>
<th>Nombres</th>
<th>Objetivos</th>
<th>Puntaje</th>
<th></th>
</tr>
@if (Model != null && Model.Count > 0)
{
int j = 0;
foreach (var i in Model)
{
<tr style="border:1px solid black">
<td>@Html.TextBoxFor(a => a[j].nombres, new { @class = "form-control"})</td>
<td>@Html.TextBoxFor(a => a[j].objetivos, new { @class = "form-control" })</td>
<td>@Html.TextBoxFor(a => a[j].puntaje, new { @class = "form-control" })</td>
<td>
@if (j > 0)
{
<a href="#" class="removecell">Remove</a>
}
</td>
</tr>
j++;
}
}
</table>
<input class="btn btn-success" type="submit" value="Save Bulk Data" />
}
If there is any way to modernize the code
JavaScript
I am open to all your proposals as long as you do not lose functionality.