1

I would like to make a event listener, for when .quantity select changes.

Since live() is depreciated, I've tried the both:

$('.variant').delegate('.quantity', 'change', function()

http://jsfiddle.net/PdA4W/

$('.variant').on('change', '.quantity', function()

http://jsfiddle.net/PdA4W/2/

The problem is, that when you click Add (and it has cloned and appended a variant div), that the event listener doesnt listen at the change on the select thats inside. No alert.

Only works with the first select

What could be the issue here?

Karem
  • 17,615
  • 72
  • 178
  • 278
  • @PSL Ofcourse, that is what i originally did - I have updated the question. – Karem Dec 26 '13 at 21:47
  • possible duplicate of [Event binding on dynamically created elements?](http://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – PSL Dec 26 '13 at 21:53

1 Answers1

1

Try this instead:

$(document).on('change', '.variant', function(){
    alert(1);
});

The DOM is not really aware that you added elements dynamically. With the code above, it pretty much ignores that, and binds the event to all the future elements indicated by your selector. http://jsfiddle.net/hescano/PdA4W/3/

From JQuery documentation: http://api.jquery.com/on/

Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on(). To ensure the elements are present and can be selected, perform event binding inside a document ready handler for elements that are in the HTML markup on the page. If new HTML is being injected into the page, select the elements and attach event handlers after the new HTML is placed into the page. Or, use delegated events to attach an event handler, as described next.

So you can either re-bind the event after every time you click the link, or do it as in the code above.

Hanlet Escaño
  • 17,114
  • 8
  • 52
  • 75