Reputation: 4462
I have the following jQuery/ajax script:
jQuery("input.button").click(function(){
jQuery.ajax({
url: 'addfav.php',
type: 'POST',
data: {'id':jQuery(this).closest("div").attr("id"),is_ajax: 1},
success: function(html) {
jQuery(this).removeClass('before');
jQuery(this).addClass('after');
jQuery(this).attr('disabled', 'disabled');
},
error: function() {
jQuery('#error').html('<div>Error! Unable to add food item.</div>');
}
});
});
Which handles clicking on buttons such as these:
<div id="32"><input type="button" class="button before"/></div>
<div id="33"><input type="button" class="button before"/></div>
The adding and removing of classes to whichever but is clicked does not work however. It works for a single button with an ID, i.e.:
jQuery("input#button1").click(function(){
But not when I use classes. What changes do I need to make to get this script to add or remove classes to whichever button is clicked when I just use a class for the button?
Upvotes: 1
Views: 3264
Reputation: 144689
You should cache the selector, try the following:
jQuery("input.button").click(function(){
var $this = $(this);
jQuery.ajax({
url: 'addfav.php',
type: 'POST',
data: {'id': $this.closest("div").attr("id"),is_ajax: 1},
success: function(html) {
$this.removeClass('before');
$this.addClass('after');
$this.attr('disabled', 'disabled');
},
error: function() {
jQuery('#error').html('<div>Error! Unable to add food item.</div>');
}
});
});
Upvotes: 2