Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

<span> jQuery .click() not working

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;         }); }); 
like image 828
Charles Harrison Avatar asked Oct 16 '13 01:10

Charles Harrison


2 Answers

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;     }); });   
like image 155
Tushar Gupta - curioustushar Avatar answered Sep 16 '22 17:09

Tushar Gupta - curioustushar


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*/ }); 
like image 32
Anton Avatar answered Sep 16 '22 17:09

Anton