ozzii ozzii - 3 months ago 16
Ajax Question

JQuery Click Handlers not Working After Ajax Page Load

I have an ASP MVC application where I have a partial view which is loaded via ajax each time a new comment is added.

However the jquery click handlers no longer work after an ajax page load.

<div id="comments">
// Jquery links don't work after ajax page load?
<ul>
<li>
<div></div>
<a href="#" class="js-delete-comment" data-comment-id="@Model.comment.Id">
<i class="fa fa-trash-o" aria-hidden="true"></i> Delete
</a>
</li>
</div>

@using (Ajax.BeginForm("Create", "Comments", null, new AjaxOptions
{
HttpMethod = "POST",
LoadingElementId = "create-post-wait",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "comments",
OnComplete = "AjaxCreatePostComplete()"
}, new { enctype = "multipart/form-data" }))
{

@* form details *@

}


My Jquery

$(function () {

DeleteComment();

}


var DeleteComment = function () {

if ($(".js-delete-comment").length === 0) {
return;
}

$(".js-delete-comment").click(function (e) {
var a = $(this); // "this" is the <a>

window.swal({
title: "Confirm",
text: "Are you sure you want to delete this comment?",
type: "warning",
showCancelButton: true
},
function () {
$.ajax({
// do stuff
})
});
});
};


var AjaxCreatePostComplete = function () {
var createButton = $("#create-post-btn");
if (createButton.length > 0) {
createButton.attr("disabled", false);
}

};

Answer

Use jQuery on().The difference between on() and click() is that on() works for dynamically added elements. Please try changing your click event like this:

$(document).on('click','.js-delete-comment',function() {
   //Add the logic for the click event here
});
Comments