1

I am trying to add a css class to my button after some ajax:

$('a.vote-up-0').click(function() {

    var id = $(this).siblings('.reply-id').val();
    var ajax_auth_token = $('#auth_token').val();


    $.post('user/?action=ajax', {
        vote_type: 'up',
        reply_id: id,
        auth_token: ajax_auth_token
    }, function(data, return_status) {   

        var json_data = jQuery.parseJSON(data);

        switch(json_data.r_message)
        {
           case "success": 
              output = "Yay it works!"; // change 
               alert(output);
               $(this).addClass('vote-up-1'); // ** the culprit **
           break;

The alert works, however it does not add the class vote-up-1 to it. There are several instances of the same class (i.e. vote-up-0) on the page, so If I change (this) to 'vote-up-0', it changes all of them. Anyone have any ideas?

1
  • put alert after the culprit line and check Commented Apr 17, 2011 at 17:34

3 Answers 3

2

Up at the top of your "click" handler, stash the this value:

var theButton = this;

Then, in your ".post()" handler:

$(theButton).addClass('vote-up-1');

The problem is that this will not refer to the button when jQuery calls your ".post()" handler. Thus, you save a copy into a local variable, and it'll be there waiting for the handler when the time comes.

Sign up to request clarification or add additional context in comments.

Comments

0

Brother: $(this).addClass('vote-up-1'); // ** the culprit ** is truly the culprit. $(this) is not available in this scope so it's better that you get the handle of the button before doing any ajax. such as:

var btnHnd = $(this); Now you can do the post stuff: $.post('user/?action=ajax', { ...

Comments

0

change this

 $(putyourbuttonidhere).addClass('vote-up-1'); 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.