Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQUERY AJAX - change class of $(this) in case of success

Tags:

jquery

ajax

I have a div. Inside that div I have multiple elements. Some elements have the class 'myClass'. I also have a button. When clicked, a foreach loop runs for each element that has the class myClass within the div. An ajaxCall is send for each element. The text color of those elements are black by default. In case of success of the ajax call. I would like to remove the class classBlackFont and add the one classGreenFont. I tried the following code which is unfortunately not switching the classes eventhough the ajax call succeeded.

$("#someDiv .myClass").each(function() {

    var ajaxData = "myAjaxData";
    $.ajax({
        type: "POST",
        url: "somefile.php",
        data: ajaxData,
        success: function(data) {

            $(this).removeClass('classBlackFont').addClass('classGreenFont');
        }
    });

});​
like image 620
Marc Avatar asked Dec 10 '22 00:12

Marc


1 Answers

this is not automatically a reference to the right object in the ajax callback. You can change that by closing over a variable that does have the right value:

$("#someDiv .myClass").each(function() {
    var $this = $(this);
    var ajaxData = "myAjaxData";
    $.ajax({
        type: "POST",
        url: "somefile.php",
        data: ajaxData,
        success: function(data) {
            $this.removeClass('classBlackFont').addClass('classGreenFont');
        }
    });

});​

or by using the context option of $.ajax():

$("#someDiv .myClass").each(function() {
    var ajaxData = "myAjaxData";
    $.ajax({
        type: "POST",
        url: "somefile.php",
        data: ajaxData,
        context: this,
        success: function(data) {
            $(this).removeClass('classBlackFont').addClass('classGreenFont');
        }
    });

});​
like image 116
Matt Ball Avatar answered Dec 30 '22 15:12

Matt Ball