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