2

I am using the AJAX GET method to return some names from a mysql database in the form of a button. This is done successfully and now when I click on one of these buttons I want it to call a javascript function which is working. When the button is clicked I also want to add a class to that specific button. Im doing it as follows -

$('.btn').click(function() {        
    $(this).addClass('btn-warning');
});

But it is not adding any class. Also this is the code I am echoing in the AJAX call -

echo "<button type='button' id=".$row['email']." class='btn names btn-link' onclick='personchange(\"".$row['email']."\",\"".$row['first_name']."\")'>".$row['first_name']."</button>";

Any help is greatly appreciated

mgherkins
  • 13,149
  • 6
  • 38
  • 68
user2636368
  • 612
  • 4
  • 9
  • 19

1 Answers1

3

if you create elements after the initial rendering of the page, you'd need to use the .on() method like this:

$('body').on('click', '.btn', function(){
  $(this).addClass('btn-warning')
});

where 'body' can be a selector for any element containing the created ones.

see http://api.jquery.com/delegate/

mgherkins
  • 13,149
  • 6
  • 38
  • 68