jQuery removeClass and addClass not working

678 Views Asked by At

I have created a button and when the user clicks on it, the current class should be replaced with a new one and vice-versa. BUT addClass or removeClass, are both not showing any effect. I haven't seen any errors or warning msgs in console log.

JQuery code:

$('.vote_btn').click(function(){
  $.ajax({
        url:'/joseph/pages/votes.php',
        type: 'post',
        //dataType:'json',
        data:{'comment_id':$(this).data('commentid')},
        success: function(data){
          if(data == 'up'){
              $(this).removeClass('fa-thumbs-o-up').addClass('fa-thumbs-up');
          } else if(data == 'reversed') {
              $(this).removeClass('fa-thumbs-up').addClass('fa-thumbs-o-up');
          } else {
            alert(data);
          }
        }
  });
});

HTML Code:

<span id="<?=$comment['id']?>" class="fa fa-thumbs-o-up vote_btn" data-commentid="<?=$comment['id']?>" data-postid="<?=$getpost['post_id']?>" data-who="<?=$comment['commenter_id']?>"></span>
2

There are 2 best solutions below

0
Zakaria Acharki On BEST ANSWER

The jQuery object $(this) no longer refers to the clicked .vote_btn. Inside the success callback, store the clicked button in a variable and use this variable inside the callback :

$('.vote_btn').click(function(){
  var _this = $(this);

  $.ajax({
        url:'/joseph/pages/votes.php',
        type: 'post',
        //dataType:'json',
        data:{'comment_id':_this.data('commentid')},
        success: function(data){
          if(data == 'up'){
              _this.removeClass('fa-thumbs-o-up').addClass('fa-thumbs-up');
          } else if(data == 'reversed') {
              _this.removeClass('fa-thumbs-up').addClass('fa-thumbs-o-up');
          } else {
            alert(data);
          }
        }
  });
});

Hope this helps.

5
SURJEET SINGH Bisht On

Try this will work :

 $('.vote_btn').click(function(){
  var curEvent=$(this);
   $.ajax({
    url:'/joseph/pages/votes.php',
    type: 'post',
    //dataType:'json',
    data:{'comment_id':$(this).data('commentid')},
    success: function(data){
      if(data == 'up'){
          $(curEvent).removeClass('fa-thumbs-o-up').addClass('fa-thumbs-up');
      } else if(data == 'reversed') {
          $(curEvent).removeClass('fa-thumbs-up').addClass('fa-thumbs-o-up');
      } else {
        alert(data);
      }
    }
   });
   });