0

I need to add an event using bind() after replaceWith(), but the elements exist only after the replaceWith() is executed. How do I add events after the elements are loaded?

My code looks something like this:

$.ajax({
    type: 'GET',
    url: trElement.find(".editRecord").attr("href") + '?id=' + tdId.html(),
    success: function(data, textStatus, jqXHR) {
        trElement.replaceWith(data);
        trElement.find(".btnEditRecord").bind("click", save);
        trElement.find(".btnCancelEditRecord").bind("click", cancel);
    }
});

If you can, please exemplifies.

Thank you very much.

maurymmarques
  • 329
  • 1
  • 3
  • 17
  • You just replaced `trElement` with `data`, so `trElement` is gone, no use adding event handlers to that, attach the event handlers to `data` instead – adeneo Sep 23 '14 at 19:24
  • Or use event delegation when the DOM is loaded, so you don't need to do anything after loading new elements dynamically. See http://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements – Barmar Sep 23 '14 at 19:26

1 Answers1

0

After calling replaceWith, the element no longer exists in the DOM. You need to bind events to the new element:

var $data = $(data);
trElement.replaceWith($data);
$data.find(".btnEditRecord").bind("click", save);
$data.find(".btnCancelEditRecord").bind("click", cancel);
Andrew Whitaker
  • 124,656
  • 32
  • 289
  • 307