Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery.inArray() not working as expected

Tags:

jquery

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>
like image 561
MFB Avatar asked Mar 25 '13 20:03

MFB


2 Answers

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)
like image 102
Justin Bicknell Avatar answered Nov 08 '22 11:11

Justin Bicknell


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

like image 3
Andy Meyers Avatar answered Nov 08 '22 11:11

Andy Meyers