17

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>
3
  • 9
    .inArray() returns an index, not a bool. Make sure to read the doc prior. Commented Mar 25, 2013 at 20:42
  • 1
    possible duplicate of jQuery.inArray not behaving as expected Commented Mar 25, 2013 at 20:44
  • this is a duplicate, sorry Commented Mar 25, 2013 at 20:46

3 Answers 3

39

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)
Sign up to request clarification or add additional context in comments.

3 Comments

But I want to check if the key IS in the array. Is that possible, or do I just reverse the logic of the function?
if the index returned by that function is > -1 than that means the key IS in the array. In other words, the above will return true if it is in the array.
Thanks, My mistake is that I think it returns a boolean value
3

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

Comments

3

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)) {

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.