Kevin Steen Hansen
Kevin Steen Hansen

Reputation: 555

jQuery - check if in array? What is wrong?

Hello Stackoverflow, im kinda stucked :(

I am doing a code where I have some divs with specific ids like 1 and 2 and 3.

Now i want it to check if my number is part of an variable or an array, it should console.log it that, that div is locked. But I can't really figure out how to solve this? Can anyone help me?

I have tried this:

var f = getXY(e.pageX, e.pageY);
var obj = [1,2,3,4];
var arr = obj;

if ($.inArray(f, obj)) {
    console.log("Dette er låst");
} else {
    if (f) {
        $fields.removeClass('hover');
        $('#f' + f).addClass('hover');   
    }
}

I want to have more then one number in the array or variable.

Thanks guys.

Upvotes: 0

Views: 383

Answers (1)

Adriano Carneiro
Adriano Carneiro

Reputation: 58615

jQuery's inArray() returns the index where element was found. So your conditional should be:

if ($.inArray(f, obj) > -1)

Upvotes: 6

Related Questions