2
var arr = [ "One", "Two", "Three" ];

$('select[name="class"]').change(function() {
    if (jQuery.inArray("blah blah", arr)) {
        alert("OK");
    }
});

this is alerting "OK", yet "blah blah" isn't in the array... what am I doing wrong?

0

3 Answers 3

9

The jQuery.inArray function always returns a value:

Description: Search for a specified value within an array and return its index (or -1 if not found).

Docs: http://api.jquery.com/jQuery.inArray/

Change your code to:

if (jQuery.inArray('blah blah', arr)) >= 0) {
    alert('Ok');
}
Sign up to request clarification or add additional context in comments.

Comments

3

try :

if (jQuery.inArray("blah blah", arr) >-1) {

instead of :

if (jQuery.inArray("blah blah", arr)) {

Comments

3

jQuery.inArray returns -1 if the item is not found. Unfortunately, -1 is a truthy value in JavaScript.

Check for -1 and you're good.

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.