1

this seems like it should be straightforward, but I'm having trouble getting it to work.

I have a .click bind to many buttons of a certain class. When that button is clicked, it passes its id to a $.post call for processing.

When the $.post call returns successfully, I'd like to remove the button and add a message to the container, but I can't seem to even access the button at that point.

Here is the .click bind:

$('.button').click(function() {
    $.post('process.php', {
        action: 'checkit'
    },
    function(result) {
        if (result == 'win') {
            // Access the button that was pressed with jQuery
        }
        else {
            alert("fail");
        }
    });
});

I've tried, $(this), this, and also setting a variable like var trigger=this as I enter the initial click function, but none of these are working. I get undefined, or it points to the actual JQuery object, not the button.

Does anyone have any insight into how I can access the button that was clicked at that point, using a jQuery wrapper, essentially something like $( triggered button ).html() so that I can manipulate the correct button?

Thanks for your time.

0

5 Answers 5

4
$('.button').click(function() {
    var clicked = $(this);
    ....

Use a local variable for temporary storage.

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

3 Comments

+1 - Inside the callback, you would then use clicked.remove().
+1 - would also reccomend the var name be $clicked so that you know it's a jQuery object.
@johndavidjohn: interesting suggestion, but reminds me too much of PHP :D
2

try this

$('.button').click(function() {
    var $button = $(this);
    $.post('process.php', {
        action: 'checkit'
    },
    function(result) {
        if (result == 'win') {
            $button.doStuff();
        }
        else {
            alert("fail");
        }
    });
});

1 Comment

Wow, I swear I tried that. Maybe I screwed up how it was typed, or mistakenly used "this" instead of $(this) somewhere. Thought I had tried all combinations after it failed to work. Thanks to everyone who commented.
0

It's quite easy to do:

$(this).foo('bar');

Comments

0

Is

$('.button').click(function() {
    $.post('process.php', {
        action: 'checkit'
    },
    function(result) {
        if (result == 'win') {
            $(this).html('something');
        }
        else {
            alert("fail");
        }
    }.bind(this));
});

working?

Comments

0

jsfiddle example of what you are attempting. Click on the text. Just keep a local variable.

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.