Nick
Nick

Reputation: 4462

jQuery/ajax script to add/remove class of button not working

I have the following script which is designed to change the look of a favourites button using ajax, as well as submit/remove data to a MySQL table:

$(document).ready(function() {
jQuery("input.before").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');
      }, 
      error: function() {
        jQuery('#error').html('<div>Error! Unable to add favourite.</div>');
      }
    });
});

jQuery("input.after").click(function(){
   var $this = $(this);
   jQuery.ajax({       
      url: 'removefav.php',
      type: 'POST',
      data: {'id': $this.closest("div").attr("id"),is_ajax: 1},
      success: function(html) {
        $this.removeClass('after');
        $this.addClass('before');
      }, 
      error: function() {
        jQuery('#error').html('<div>Error! Unable to remove favourite.</div>');
      }
    });
});
});

Which is triggered by clicking one of several buttons, i.e.:

<div id="32"><input type="button" class="button before"/></div>
<div id="33"><input type="button" class="button before"/></div>

The first section of the script removes the class 'before' and adds the class 'after' as expected, but when I then try to click on a button with the class 'after', the second section of the script isn't working, i.e. the class of the button is not changed back to 'before'. Could someone let me know why this isn't working?

Upvotes: 1

Views: 2589

Answers (1)

Musa
Musa

Reputation: 97672

Your first click handler is bound to the buttons with the before class at that time i.e. the items that was returned by jQuery("input.before") and same for the second handler, to handle events for buttons with a specific class anytime use event delegation with .on()

$(document).ready(function() {
jQuery(document).on("click", "input.before", 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');
      }, 
      error: function() {
        jQuery('#error').html('<div>Error! Unable to add favourite.</div>');
      }
    });
});

jQuery(document).on("click", "input.after", function(){
   var $this = $(this);
   jQuery.ajax({       
      url: 'removefav.php',
      type: 'POST',
      data: {'id': $this.closest("div").attr("id"),is_ajax: 1},
      success: function(html) {
        $this.removeClass('after');
        $this.addClass('before');
      }, 
      error: function() {
        jQuery('#error').html('<div>Error! Unable to remove favourite.</div>');
      }
    });
});
});

Upvotes: 3

Related Questions