Keyboard event does not work Jquery

2

I wonder why this event does not work with some keys. The key I want is seta para baixo (40) , but it does not work. The Enter (13) and letras e números keys work normally. I've removed all the Jquery code, and nothing.

$('input[name=buscar]').keypress(function(e) {
    console.log(e.which);
    if(e.which == 40) {
        alert('You pressed enter!');
    }
});
    
asked by anonymous 08.04.2016 / 12:52

1 answer

4

You should use the keydown event in this case, because the keypress event will not be triggered by keys that are not "printable", such as keyboard arrows, for example.

  

The keypress event is an element when the browser registers   keyboard input. This is similar to the key 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 keydown event can be used to capture the Shift , ESC and Delete
  • Event keypress can actually capture the keyboard arrows in some browsers, but keydown is more reliable for this scenario, as the documentation itself indicates
  • You should use the .ctrlKey , .altKey and .shiftKey of the event object to verify that the 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><inputtype="text" name="buscar" />

Source: link link

    
08.04.2016 / 13:02