1

I'm not able to bind jQuery events to dynamically created list items.

It's the event on btnRemoveItem that is not triggering after begin added by jQuery.

$('#btnAddStore').on('click', function(){
  (...)
  $.ajax({
    success: (function(result) {
      (...)
      var li = jQuery('<li/>', {
          'id': object['id']
         }).append('<span title="Remove item from list" class="btnRemoveItem"></span>')
           .append('<span class="text">' + name_adr[0] + '</span>')
           .append('<span class="address">' + name_adr[1] + '</span>');

      $(li).appendTo('#'+ country + ' ul');
    }
  });
});

I've looked at similar questions in here, but I've not found any answers that solves my problem. What am I missing from this code?

Steven
  • 19,224
  • 47
  • 152
  • 257
  • possible duplicate of [Events triggered by dynamically generated element are not captured by event handler](http://stackoverflow.com/questions/12829963/events-triggered-by-dynamically-generated-element-are-not-captured-by-event-hand) – Felix Kling Apr 17 '13 at 11:09

3 Answers3

9

Use .on() this way

$(document).on('click','#btnAddStore', function(){...});
Adil Shaikh
  • 44,509
  • 17
  • 89
  • 111
  • Thanks for the tip. It didn't work just using this on the `Add Store` function, but doing the same on the `Remove store` function sovled my problem. Does this mean I should always use this method when using the `.on()` event? – Steven Apr 17 '13 at 11:21
  • 1
    If your element is being added dynamically,you should use `.on()` this way. – Adil Shaikh Apr 17 '13 at 11:29
2

try this

$(document).on('click','#btnAddStore', function(){...});

$('#btnAddStore').on("scroll", ....) binds the scroll event to only those elements which are present at the time of execution of this statement, ie if any new element with class wrapper1 is added dynamically after this statement is executed then the event handler will not get executed for those elements.

$(document).on("scroll","#btnAddStore", ...) on the other hand will register one event handler to the document object and will make use of event bubbling to invoke the handler whenever scrolling happens within an element with class `wrapper``, so it will support dynamic addition of elements.

See here

Community
  • 1
  • 1
PSR
  • 39,804
  • 41
  • 111
  • 151
1

Use delegation with .on():

$(document).on('click', '#btnAddStore', function(){...});
A. Wolff
  • 74,033
  • 9
  • 94
  • 155