Steven
Steven

Reputation: 19425

Dynamic created content is not binding jQuery events

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?

Upvotes: 1

Views: 1223

Answers (3)

PSR
PSR

Reputation: 40318

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

Upvotes: 2

A. Wolff
A. Wolff

Reputation: 74420

Use delegation with .on():

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

Upvotes: 1

Adil Shaikh
Adil Shaikh

Reputation: 44740

Use .on() this way

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

Upvotes: 9

Related Questions