2

I am trying to change the text of a button when clicked after doing an ajax call. Why doesn't this work?

HTML

<button type="submit" class="register-button">REGISTER</button>

JS

$(".register-button").click(function () 
{
    $.ajax({
        //some ajax stuff
    }).
    success(function(){
        console.log("done");
        $(this).html("Registered");
        //$(this).hide(); doesn't work either
    });
});
dashtinejad
  • 6,193
  • 4
  • 28
  • 44
aandis
  • 4,084
  • 4
  • 29
  • 40

4 Answers4

4

this inside success is not the button. Try this - excuse the pun:

$(".register-button").click(function () 
{
        var thisButton = this;

        $.ajax({
            //some ajax stuff
        }).
        success(function(){
            console.log("done");
            $(thisButton).html("Registered");
            //$(this).hide(); doesn't work either
        });
});
Donal
  • 31,121
  • 10
  • 63
  • 72
2

this inside your success callback, is the object which passed to $.ajax. You should keep reference to your element before:

$(".register-button").click(function () {
    var $elem = $(this);

    $.ajax({
        //some ajax stuff
    }).success(function(){
        console.log("done");
        $elem.html("Registered");
        $elem.hide();
    });
});

jsFiddle Demo.

dashtinejad
  • 6,193
  • 4
  • 28
  • 44
1

this takes on new scope. So store it before the function declaration:

$(".register-button").click(function () 
{
    var that = this;
    $.ajax({
        //some ajax stuff
    }).
    success(function(){
        console.log("done");
        $(that).html("Registered");
        //$(that).hide(); should work
    });
});
ne1410s
  • 6,864
  • 6
  • 55
  • 61
0

try this one:

$(".register-button").click(function () {
        var that=this;
        $.ajax({
            //some ajax stuff
            success:function(){
                console.log("done");
                $(that).html("Registered");
                $(that).hide();
            });
        })
});
Amin Jafari
  • 7,157
  • 2
  • 18
  • 43