Syns
Syns

Reputation: 127

Assign function result to variable

I have this function:

function validateVip(){ 
    $("table[id=table-pss] tbody tr").each(function() {
        var keval = $(this.cells[4]).find('input');
        var data = $(keval[0]).val();
        console.log("result: " + data);
        console.log(data.includes([vip]));
        var x;                      
        if ((data.includes([vip])) == true)
        {
            x = "yay";
            console.log("Vip Exists");                          
        }
        else
        {
            x = "nay";
            console.log("No VIP");
        }                       
        return x;
  });
}

Whenever I call it, it always return "undefined". Here is how I call the function validateVip:

var isVip = validateVip();
            console.log("is vip:" + isVip);

Can someone show me what I did wrong?

Thank you.

Upvotes: 0

Views: 401

Answers (1)

Maxime Helen
Maxime Helen

Reputation: 1412

The value of x is returned by the callback passed to $().each, which does nothing

You need to define the variable x in the upper scope:

function validateVip() {
    var x;
    $("table[id=table-pss] tbody tr").each(function() {
        var keval = $(this.cells[4]).find('input');
        var data = $(keval[0]).val();
        console.log("result: " + data);
        console.log(data.includes([vip]));

        if ((data.includes([vip])) == true) {
            x = "yay";
            console.log("Vip Exists");
        } else {
            x = "nay";
            console.log("No VIP");
        }
    });
    return x;
}

Note that x will be equaled to the last item assignment, iterated using each

Upvotes: 1

Related Questions