MFB
MFB

Reputation: 19807

jQuery.inArray() not working as expected

What am I doing wrong here? The idea is that I can separate the arrow key presses from anything else, but the every key press is firing the alert 'you pressed an arrow key'. Any help would be great!

jsFiddle here or:

<input id='foo'>

<script>

$('#foo').keyup(function (e) {
    var key = e.keyCode;
    if ($.inArray(key, [37, 38, 39, 40])) {
        alert('you pressed an arrow key');
    } else {
        alert("you didn't press an arrow key");
    }
});

</script>

Upvotes: 17

Views: 21061

Answers (3)

user1980347
user1980347

Reputation:

The $.inArray method returns the index of the element if it is in the array, and if it is not in the array it returns -1, so you can't use it as an if condition. Change it to:

if($.inArray(key, [37, 38, 39, 40]) >= 0)) {

}

Upvotes: 3

Andy Meyers
Andy Meyers

Reputation: 1581

The jQuery inArray function returns the index of the value. For the left arrow key (37) it is returning 0 and it is being interpreted as false. You should change your code to be >=0

   if ($.inArray(key, [37, 38, 39, 40]) > -1) 

inArray

Upvotes: 3

Justin Bicknell
Justin Bicknell

Reputation: 4808

You have to check if it returns an index > -1. The index is -1 if there is no occurrence of the key in the array:

if ($.inArray(key, [37, 38, 39, 40]) >  -1)

Upvotes: 39

Related Questions