Leggy
Leggy

Reputation: 682

OOP - Accessing public "this" inside each

I'm trying to create a function to loop through some table rows but I need to use this.isempty instead of isempty. How do I access this inside of an each loop.

Code:

function checkValues(look) {
    this.isempty = 1;   
    this.search = $(look).find("input").each(function(){                        
        if ($.trim($(this).val())!="") {
            this.isempty = 0;
        }
    }); 
    return this.isempty;
}

Obviously the this.isempty = 0; will not work. How can I do this?

Upvotes: 0

Views: 41

Answers (2)

rdubya
rdubya

Reputation: 2916

Do you need to reference this because of a constraint in your code? Would the following work?

function checkValues(look) {   
    var isEmpty = 1;
    $(look).find("input").each(function(){                        
        if ($.trim($(this).val())!="") {
            isEmpty = 0;
            return false; // Breaks out of the loop for a little performance boost
        }
    }); 
    return isEmpty;
}

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388316

You can use a closure variable in this case to refer isempty

function checkValues(look) {
    this.isempty = 1;
    var self = this;
    this.search = $(look).find("input").each(function () {
        if ($.trim($(this).val()) != "") {
            self.isempty = 0;
        }
    });
    return this.isempty;
}

But a more appropriate way here is to use .filter() like

function checkValues(look) {
    this.isempty = 1;
    this.search = $(look).find("input").;
    this.isempty = this.search.filter(function () {
        return $.trim(this.value) != '';
    }).length > 0;
    return this.isempty;
}

Upvotes: 2

Related Questions