Sid
Sid

Reputation: 170

Conditional addClass not working for each elements with same class

Les say I have some buttons with same class. On page load I am checking some value using ajax for each button. Depending on returned value of ajax request I want to add some class to the buttons, but it is not working,

$(document).ready(function(){
    $('.add-remove-permissoion').each(function(){
        var child = $(this).val();
        var parent = $('#parent-name').text();
        $.get('my-url', function(data){
            if(data == 1){
                $(this).addClass('glyphicon glyphicon-ok');
            }else{
                $(this).addClass('emptybox-blank');
            }
        });
    });
});

I have checked that my ajax request is returning correct data. What is that I am doing wrong here?

Upvotes: 1

Views: 122

Answers (3)

Ram
Ram

Reputation: 144659

this in the context of the $.get handler doesn't refer to the element of the current iteration. Each function has it's own this value. You have several options.

  1. Use the second parameter of the each callback.

    $('.add-remove-permissoion').each(function(index, element) {
    
  2. Use $.proxy or Function.prototype.bind method for setting the this value of the handler.

    $.get('my-url', function(data) {
        // ...
    }.bind(this));
    
  3. Cache the this value of the each handler and use it in your $.get handler.

    var elem = this;
    $.get('my-url', function(data) {
        // ...
        $(elem)...
    });
    

Also note that there is a syntax error in your code:

$.get('my-url'}, function(data){
// -----------^

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388316

The problem is the this reference inside the ajax callback, in the success callback this refers to the jqXHR object not the dom element reference that is why it is not working.

You can use a closure variable as given below to fix the problem

$(document).ready(function () {
    $('.add-remove-permissoion').each(function () {
        var $this = $(this),
            child = $this.val();
        var parent = $('#parent-name').text();
        $.get('my-url', {}, function (data) {
            if (data == 1) {
                $this.addClass('glyphicon glyphicon-ok');
            } else {
                $this.addClass('emptybox-blank');
            }
        });
    });
});

Upvotes: 2

renakre
renakre

Reputation: 8291

Problem is $(this) within ajax call does not refer to the button clicked.

Replace $(this).addClass with myElement.addClass. Create myElement within click event just before the ajax call: var myElement = $(this).

Upvotes: 1

Related Questions