Reputation: 1729
I create link button, if it clicked, it will add textboxes with a delete link automatically. The problem is after textboxes and a delete link is added, when a delete link is clicked, it cannot delete the textbox. How to solve this?
View
@using (Html.BeginForm())
{
<div id="editorRows">
@foreach (var item in Model)
{
Html.RenderPartial("GiftEditorRow", item);
}
</div>
@Html.ActionLink("Add another...", "BlankEditorRow", null, new { id = "addItem" })
<input type="submit" value="Finished" />
}
@section Scripts {
<script>
$(document).ready(function () {
$("#addItem").click(function () {
$.ajax({
url: this.href,
cache: false,
success: function (html) {
$("#editorRows").append(html);
}
});
return false;
});
$("a.deleteRow").on("click", function () {
$(this).parents("div.editorRow:first").remove();
return false;
});
});
</script>
}
Partial View for adding textboxes dynamically:
@model MvcApplication1.Models.Gift
@using MvcApplication1.Helpers
<div class="editorRow">
@using (Html.BeginCollectionItem("gifts"))
{
<p>
Item: @Html.TextBoxFor(x => x.Name)
Value: @Html.TextBoxFor(x => x.Price, new { size = 4 })
<a href="#" class="deleteRow">delete</a>
</p>
}
</div>
Upvotes: 0
Views: 84
Reputation: 18873
Since you are generating HTML dynamically with jquery you have to use event delegation .
Instead of
$("a.deleteRow").on("click", function () {
$(this).parents("div.editorRow:first").remove();
return false;
});
Try
$(document).on("click", "a.deleteRow" ,function () {
$(this).parents("div.editorRow:first").remove();
return false;
});
Read More Here.
Upvotes: 2
Reputation: 319
replace
$("a.deleteRow").on("click", function () {
$(this).parents("div.editorRow:first").remove();
return false;
});
with
$(document).on("click","a.deleteRow", function () {
$(this).parents("div.editorRow:first").remove();
return false;
});
Upvotes: 2