jQuery post success data not in the DOM

140 Views Asked by At

My problem is the following, the jQuery Post success method returns some data , that data I'm prepending to a div but it appears that the data what I'm prepending is not in the DOM.

jQuery Post code:

$('#form').submit(function() {

  var text = $("#input").val();

  $.ajax({
     type: "POST",
     url: "file.php",
     data: "name=" + text,
     success: function(data) {
      $("#app").prepend("<span class='delete'>" + data + "</span>");
     }
  });

    return false;
});

This is the code what deletes the span but it's not deleting the prepended element.

$('.delete').on('click' , function() {

    $(this).hide();

});
1

There are 1 best solutions below

0
On BEST ANSWER

The problem is that the span elements did not exist when the click handler was bound, so the event handler is not triggered. You need to use event delegation to capture events on elements that don't exist yet:

$('#app').on('click', '.delete', function() {
    $(this).hide();
});

The handler is now bound to #app, which will always exist. Events that originate on child elements "bubble" up and are triggered on their parents as well, so all click events that are bound to descendant elements of #app trigger this handler if the originating element matches .delete.