Matt Price
Matt Price

Reputation: 1401

Check if input field value is included in array - Jquery

I'm trying to fire a function if an input field's value is equal to that of a number in an array.

I have my code below, but it doesn't seem to work!!

var num1 = $("#people-number").val();
var Numberarray = [1,3,5,7,9];

if ($.inArray(num1,Numberarray) > -1) {
     $("#valid-people").hide();
     $("#non-valid-people").fadeIn();   
}

Any tips would be appreciated.....

Upvotes: 0

Views: 1294

Answers (3)

Fernando Jorge Mota
Fernando Jorge Mota

Reputation: 1554

Test it with:

var num1 = $("#people-number").val(); var Numberarray = [1,3,5,7,9];

if ($.inArray(parseInt(num1),Numberarray) > -1) {
    $("#valid-people").hide();
    $("#non-valid-people").fadeIn();   
}

And return any result. Here it works: http://jsfiddle.net/fjorgemota/q6WJA/

Upvotes: 0

xdazz
xdazz

Reputation: 160833

You need to cast num1 to number.

if ($.inArray(+num1,Numberarray) > -1)

or

if ($.inArray(parseInt(num1, 10),Numberarray) > -1)

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388316

It is because the array has int values and the the value you are testing is a string

$.inArray(parseInt(num1),Numberarray)

Demo: Fiddle

Upvotes: 1

Related Questions