So, I created a delete "button" in a span, but for some reason I can't get the .click() to fire. Any ideas? I'm new to jQuery and am thinking that it's something obvious. I tested in Chrome and Safari with no luck.
CSS:
.delete_button { cursor:pointer; color: #fff; border: 1px solid #FFF; border-radius: 15px; background: #AAA; font-size: 8px; line-height: 0px; padding: 0px 2px 0px 2px; }
HTML/PHP:
<span class="delete_button" id="delete_<? echo $some_id; ?>">X</span>
jQuery:
$(document).ready(function() { $('.delete_button').click(function() { var transaction_id = $(this).attr('id').replace('delete_',''); alert("Delete transaction #" + transaction_id); return false; }); });
use .on()
As your span is added dynamically so it is not present at the time DOM ready or page load.
So you have to use Event Delegation
Syntax
$( elements ).on( events, selector, data, handler );
like this
$(document).on('click','.delete_button',function(){ // code here });
or
$('parentElementPresesntAtDOMready').on('click','.delete_button',function(){ // code here });
your code becomes
$(document).ready(function () { $(document).on('click', '.delete_button', function () { var transaction_id = $(this).attr('id').replace('delete_', ''); alert("Delete transaction #" + transaction_id); return false; }); });
It seems like the span is dynamically created, you need to use event delegation. Bind it to the closest static parent or document
$(document).on('click','.delete_button',function(){ /*Your code*/ });
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