The keypress
will run while the key has been pressed, the problem is that it works only for alphanumeric values, punctuation and etc. Does not work with Alt
, Shift
etc..
Use the keydown
, it will activate the trigger before any other browser action.
According to the documentation¹:
The event keydown
is triggered when a key is pressed down. Unlike the event keypress
, the event keydown
is fired for keys that produce a character value and for keys that do not produce a character value.
$("#txt_cep").keydown(function (e) {
if (e.keyCode == 9) {
alert("Tab");
} else if (e.which == 13) {
alert("Enter");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="txt_cep" />
Obs.: Chrome does not trigger the event keypress
for known keyboard shortcuts ¹
Reference 1: https://developer.mozilla.org/en-US/docs/Web/Events/keypress