I have the following HTML element:
<a href='#' class='receipt' id='{some id. generated dynamically}'>Receipt</a>
I have the following jQuery, to handle a click:
$('.receipt').click(function () {
alert('hai');
alert($(this).attr('id'));
});
For some reason, when I click....nothing happens. I originally was trying to use mouseover, but I thought I was doing it incorrectly so I tried click. No dice..am I missing something here?
UPDATE - This is how it ended up working, I'm using .live over .on as Jeff B suggested, but I'm sure .on would work just as well.
$('.receipt').live('click', function () {
alert('hai');
alert($(this).attr('id'));
});
UPDATE 2 - .on will be replacing .live in the future, so you should probably use .on.
You mention that the id is generated dynamically. If the element is created after the handler is created, it will not work.
For dynamic elements, use .on():
$('body').on('click', '.receipt', function() {
alert('hai');
alert($(this).attr('id'));
});
In this case, body is the element that essentially handles the click, once the event travels up the DOM, and then it makes sure it originated in .receipt. Instead of body, you could use any element that is a parent/ancestor of the .receipt divs, preferably closer.
Because body handles the click, the handler is attached to something that always exists. This way you can add and remove .receipt elements without worrying about the handler disappearing.
Change $('receipt') to $('.receipt')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With