MFB MFB - 11 months ago 64
jQuery Question

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'>


$('#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");



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)