Keyboard event does not work Jquery

Asked

Viewed 1,072 times

2

I wonder why this event does not work with a few keys. The key I wish is the seta para baixo (40), but this one doesn’t work. Already the keys Enter (13) and the letras e números work normally. I have removed all Jquery code, and nothing.

$('input[name=buscar]').keypress(function(e) {
    console.log(e.which);
    if(e.which == 40) {
        alert('You pressed enter!');
    }
});

1 answer

4


You must use the event keydown in this case, because the event keypress will not be fired by keys that are not "printable", like the arrow keys on the keyboard, for example.

The keypress Event is sent to an element when the browser Registers Keyboard input. This is similar to the keydown Event, except that Modifier and non-printing Keys such as Shift, Esc, and delete Trigger keydown Events but not keypress Events. Other Differences between the two Events may arise Depending on Platform and browser.

Notes

  • The event keydown can be used to capture keys Shift, ESC and Delete
  • The event keypress can actually capture the arrow keys on some browsers, but the keydown is more reliable for this scenario, as indicated by the documentation itself
  • You must use the properties .ctrlKey , .altKey and .shiftKey of the object Event to check if the keys ctrl, alt and shift were fired

Code working with keydown

$('input[name=buscar]').keydown(function(e) {
    console.log(e.which);
    if(e.which == 40) {
        alert('You pressed enter!');
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="text" name="buscar" />

Source: https://stackoverflow.com/questions/19347269/jquery-keypress-arrow-keys https://api.jquery.com/keypress/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.