Chriz74 Chriz74 - 6 months ago 18
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

button. The problem is the
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 ='deletecmnt_', '');

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

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

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")) {





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


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.


    $("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: