Nate Pet
Nate Pet

Reputation: 46222

jquery check variable values

In jQuery I have the following 4 variables.

var add
var city
var state
var zip

I need to check to see that any one of the above have a value. If none have a value that is OK. If all of them have a value that is OK.

Just need to check that at least one of them do not have a value. Not sure what is the most efficient way of doing this.

Upvotes: 0

Views: 8081

Answers (6)

Florian Margaine
Florian Margaine

Reputation: 60717

var check = [ add, city, state, zip ].every( function ( v ) { return !!v } )

Just for the sake of showing off.

Explaination: the every method loops through all the array and returns false if one of the conditions returns false and stops immediately the loop. If all the loops return true, true is returned.

PS: v is for "variable".

Upvotes: 4

Ram
Ram

Reputation: 144659

if( add.length == 0 || zip.length == 0 || city.length == 0 || state.length == 0) {    
    alert("at least one of the variables has no value");      
};   else if (add.length == 0 & zip.length == 0 & city.length == 0 & state.length == 0) {
         alert("all of the variables are empty");
     }; else { alert("okay"); }

Upvotes: 0

thecodeparadox
thecodeparadox

Reputation: 87073

if(!add || !city || !state || !zip) {
    console.log('exists var with no value');
}

Upvotes: 0

Givius
Givius

Reputation: 1008

to check i a variable has a value assign it to it you can do:

var myVar
....
if (typeof myVar === 'undefined'){
  // here goes your code if the variable doesn't have a value
}

Upvotes: 0

rlemon
rlemon

Reputation: 17666

var check = (function(a, b, c, d) {
    return !!a && !!b && !!c && !!d;
}(add, city, state, zip));

console.log(check);

another method... lets learn some new techniques today!

this will actually check to see if the value is not false. anything else is ok (strings, numerics, TRUE).

Upvotes: 3

Shehzad
Shehzad

Reputation: 2940

Simply

if (yourVar)
{
    // if yourVar has value  then true other wise false.
}

Hope thats what you required..

Upvotes: 0

Related Questions