1

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

3 Answers 3

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

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

5 Comments

Yes, I see that removes the if statement, I just couldn't get it to work! Id be very interested in knowing how, smaller code is always better!
@Dirty, I had a typo initially. == instead of !=. This version should be correct, and I consider it more readable.
I apologize, but I cannot get $.validator.addMethod( "ReutersNA", function(value, element) { var selectedCountry = $("#Country").val(); var NorthAmerica = new Array("USA","CAN","MEX"); return $.inArray(selectedCountry,NorthAmerica) == -1; }, "Cannot select Reuters News outside of North America." ); to work
@Dirty, I meant my original code, which had ==, was wrong. My current answer (with !=), should be correct.
@Josh K - I need to add in there to only do this if "#IQBAS, #IQPRE" are :checked
1

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 (i.e. 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) 

1 Comment

Thanks for all the help. using >0 caused it to return false on USA the first(0) item in the array. Much appreciated!
0

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; } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.