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/