I am using asp.net MVC 3, and I am trying to remove a LI that was added through a HTTP Post.
I am able to remove the item that already in the UI but not the new item got added.
Here is UI code:
<a href="#" id="addNew">Add New</a>
<div id="ulList">
<ul>
<li id="li_1"><a href="#" id="a_1" class="aLink">1</a></li>
<li id="li_2"><a href="#" id="a_2" class="aLink">2</a></li>
<li id="li_3"><a href="#" id="a_3" class="aLink">3</a></li>
</ul>
</div>
<script type="text/javascript">
$('#addNew').on("click", function () {
$.ajax({
url: '@Url.Action("AddItem")',
type: "POST",
data: { id: 4 },
success: function (data) {
$('#ulList ul').append(data);
}
});
});
$('.aLink').on("click", function () {
RemoveItem($(this).attr('id'));
});
function RemoveItem(id) {
id = id.substring(id.indexOf("_") + 1);
$.ajax({
url: '@Url.Action("RemoveItem")',
type: "POST",
data: { id: id },
success: function (event, ui) {
$('#li_' + id).remove();
}
});
}
</script>
The AddItem calls teh AddItem in code behind and returns simple string.
[HttpPost]
public ActionResult AddItem(int id)
{
return Content(@"<li id=""li_4""><a href=""#"" id=""a_4"" class=""aLink"">4</a></li>");
}
The Item does get added, but notice that when you click on the new added item “4”, it doesn’t get removed or the call is made to the Remove the item. Please advice to what I need to do in order for this to work.
Your jQuery event handler will only attach events to elements that were initially on the page with
.on. In order for your events to work on dynamicly added elements you have 2 options depending on what version of jQuery your running.V1.4 -> 1.7 .delegate()
v1.7+ amended .on() -> retarget to point to parent container