admin管理员组

文章数量:1356953

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.

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.

Share Improve this question edited Apr 19, 2012 at 17:02 Sampson 269k76 gold badges545 silver badges568 bronze badges asked Apr 19, 2012 at 16:33 Nate PetNate Pet 46.4k127 gold badges274 silver badges420 bronze badges 1
  • 2 Are you sure you don't have the following four variables in Javascript? :P – rlemon Commented Apr 20, 2012 at 12:30
Add a ment  | 

6 Answers 6

Reset to default 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".

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

Simply

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

Hope thats what you required..

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
}
if(!add || !city || !state || !zip) {
    console.log('exists var with no value');
}
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"); }

本文标签: javascriptjquery check variable valuesStack Overflow