nao
nao

Reputation: 1198

JQuery: .on handlers not attaching to dynamically added elements

I'm creating a comment system right now. When the page loads, there is a box to create a new comment, as well as a number of comments with reply buttons. The reply buttons when clicked clone and append the comment text box like so:

$(document).ready(function(){
  $('.reply-button')
    .one('click', function(){
      var parent_id = $(this).parent('.comment').attr('id')
      var parent_id_field = "<input value='" + parent_id + "' type='hidden' name='comment[parent_id]'' id='comment_parent_id'>"
      $(this).replaceWith($('#master-comment-form').clone().attr('id', "reply-div-" + parent_id))
      $('#' + "reply-div-" + parent_id).find('.field').append(parent_id_field)
    });

When the box is filled and the form is submitted, I run this script to append the comment baed on the response of the AJAX call.

jQuery(function () {
    //target comment-form from comment form partial
    $(".comment-form-div")
        .on("ajax:beforeSend", function (evt, xhr, settings) {
            console.log("Ajax request sent")
            return $(this).find('text_area')
                .addClass('uneditable-input')
                .attr('disabled', 'disabled');
        })
        .on("ajax:success", function (evt, data, status, xhr) {
            console.log("Ajax request successful")

            $(this).find('text_area')
                .removeClass('uneditable-input')
                .removeAttr('disabled', 'disabled')
                .val('');
            return $(xhr.responseText).hide().insertAfter($(this)).show('slow');
        });
});

The issue is that the JQuery to append the comment only works on the original reply box. The new reply boxes -- the ones generated from the .clone on the comments -- do not appear to have a handler attached to them and while the form still submits, the JQuery .on for the AJAX call is never run.

Upvotes: 2

Views: 45

Answers (1)

Jack Guy
Jack Guy

Reputation: 8523

This may be one of the situations where it's appropriate to use delegated event handling

$(document).on('ajax:beforeSend', '.comment-form-div', function (evt, data)
{
   //do something
});

The event will be bound to the document but will check to see if it's being applied to the child selector, the second argument of .on

Upvotes: 2

Related Questions