简体   繁体   中英

Need help comparing an array against a var

Hi I can't seem to get this right. Basically if the value of a select list is either "USA", "CAN", or "MEX" it should return true. any other value should return false. This only returns true if the value is "USA"

$.validator.addMethod(
"ReutersNA",
function(value, element) {
    var selectedCountry = $("#Country").val();
    var NorthAmerica = new Array("USA","CAN","MEX");
    if($.inArray(selectedCountry,NorthAmerica)) {
        return false;
    } else return true;
}, "Cannot select Reuters News outside of North America."
);
return $.inArray(selectedCountry,NorthAmerica) != -1;

$.inArray returns the index where it's found, or -1. The index 0 is falsy, so in that case it went to the else clause and returned true. For everything else, it returned false.

I am not a Jquery expert but this is from the Jquery Site for .inArray, You should be aware that inArray returns the index and:

"Because JavaScript treats 0 as loosely equal to false (ie 0 == false, but 0 !== false), if we're checking for the presence of value within array, we need to check if it's not equal to (or greater than) -1."

Therefore you should be trying != -1 or >-1 in your if statement as follows

if($.inArray(selectedCountry,NorthAmerica) != -1)  

or

if($.inArray(selectedCountry,NorthAmerica) > -1)  

It returns the index. and your having it return false if it did find it!

try changing it to this:

if($.inArray(selectedCountry,NorthAmerica) > 0) {
    return true;
} 
else{

   return false;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM