views:

56

answers:

2
$(document).ready(function() {
    $(".delete_user_button").click(function(){
        var username_to_delete = $(this).attr('rel');
        $.ajax({
            type:"POST",
            url:"/delete/",
            data:{'username_to_delete':username_to_delete},
            beforeSend:function() {
                $(this).val("Removing...");
            },
            success:function(html){
                $("div.delete_div[rel=" + username_to_delete + "]").remove();
            }
            });
        return false;
    });
});

Why doesn't $(this).val() work? I'm trying to change the text of the button when the user clicks remove.

+10  A: 

In your event handler (beforeSend), this refers to the XMLHttpRequest object used for the ajax call, not your original this of the click event handler. You should "capture" it in a variable first:

$(document).ready(function() {
    $(".delete_user_button").click(function(){
        var element = $(this);
        var username_to_delete = element.attr('rel');
        $.ajax({
            type:"POST",
            url:"/delete/",
            data:{'username_to_delete':username_to_delete},
            beforeSend:function() {
                element.val("Removing...");
            },
            success:function(html){
                $("div.delete_div[rel=" + username_to_delete + "]").remove();
            }
            });
        return false;
    });
});

This mechanism is called "closures". For an interesting explanation of this, check this link:

http://www.bennadel.com/blog/1482-A-Graphical-Explanation-Of-Javascript-Closures-In-A-jQuery-Context.htm

Philippe Leybaert
A: 

Without more knowledge about the context or analysing the script itself: Keep in mind that, in certain environments, it might be possible that $ itself does not work and needs to be replaced with jQuery - I've seen this in Liferay.

I guess this is not your problem here, but it might come in handy for others looking for this problem from another context.

Olaf