Reputation: 2522
I have some dynamically created buttons:
<input type='button' id='remove_"+ii+"' class='removeItem' value='remove'>
the value of ii is irrelevant.
I am trying to listen for any of these buttons to be clicked and do something:
$(document).on('click',$('.removeItem'),function(){
alert($(this).attr('id'));
});
however, the alert is giving me "undefined". At the very least i would expect to see "remove_"..
what am i missing?
Upvotes: 0
Views: 99
Reputation: 388316
I think the problem is the way you are registering the event handler. In your case you are passing a jQuery object as the second parameter while you are trying to use event delegation.
For event delegation you need to pass a string selector as the second param to .on()
$(document).on('click', '.removeItem',function(){
alert($(this).attr('id'));
});
Demo: Fiddle
Why?
Because on() method allows to pass a object as its parameter, which will be passed to the handler in the event.data
property, so your handler instead of using event delegation is adding an handler to the document
object with event data as a jQuery object. So this
inside the handler is referring to the document
object which does not have the id
property
Demo: Fiddle
Upvotes: 2