0

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.

1
  • 2
    Are you sure you don't have the following four variables in Javascript? :P Commented Apr 20, 2012 at 12:30

6 Answers 6

4
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".

Sign up to request clarification or add additional context in comments.

Comments

3
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).

2 Comments

Meh, that's just ugly :p although fun ^^
Btw, this will also return false if there is an empty string.
0

Simply

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

Hope thats what you required..

Comments

0

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
}

Comments

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

Comments

0
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"); }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.