Dr.Ajay Kashyap

Dr.Ajay Kashyap

  • NA
  • 521
  • 277.6k

How to assign id to dynamic create textbox In Mvc

Feb 6 2017 1:01 AM
View:- 
 
<table id="dataTable" border="0" cellpadding="0" cellspacing="0">
<tr>
@Html.Label("Category Name", htmlAttributes: new { @class = "control-label col-md-2 required" })
</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].Category, new { @class = "form-control", @placeholder = "Enter Category Name", @style = "text-transform: capitalize", @onKeyPress = "return ValidateAlphaComma(event);", @id="Category" })
</td>
<td>
@if (j > 0)
{
<a href="#" class="remove">Remove</a>
}
</td>
</tr>
j++;
}
}
</table>
 
 
 
 
<script language="javascript">
$(document).ready(function () {

//1. Add new row
$("#addNew").click(function (e) {
e.preventDefault();
var $tableBody = $("#dataTable");
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('Remove');
$.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
$('a.remove').live("click", function (e) {
e.preventDefault();
$(this).parent().parent().remove();
});

});
</script>

Answers (3)