Chriz74 Chriz74 - 4 months ago 13
jQuery Question

Attaching event to dynamic inserted button on page with jquery using .on()

I have a page where I return users posts, these posts can be commented on the fly using some jquery code, after a new comment is posted I insert the new comment under the post along with a

Delete
button. The problem is the
Delete
button doesn't work on the newly inserted element unless I reload the page. I read that the solution is using the .on() method however I am a little confused re how to implement this.
I have one function that updates the post part with the newly inserted comment and this is the function that deletes the comment:

$(document).ready(function () {

$("button[id*='deletecmnt_']").click(function () {

var id = this.id.replace('deletecmnt_', '');

var comment_card_id = ('#comment_' + id);

var token = $(this).data('token');

$.ajax({
url: '../comment/' + id,
type: 'post',
data: {_method: 'delete', _token: token},
success: function () {


// Checks for display of comment card and removes it
if ($(comment_card_id).is(":visible")) {

$(comment_card_id).fadeOut("fast");

}
}
})

})

});


I don't understand what needs to be changed here and how.

Answer

You need to use event delegation for elements added dynamically. In your .on() method, you need to add the selector that you want the handler attached to after it's created.

 $(document).ready(function(){ 

    $("body").on("click", "button[id*='deletecmnt_']", function () {
    // codes
    }
 });

This will listen for clicks on elements not yet created that match your selector. Here's the JQuery API doc page for more info: http://api.jquery.com/on/