The keypress
will run as long as the key is pressed, the problem is that it works only for alphanumeric values, punctuation, and so on. It does not work with Alt
, Shift
etc.
Use keydown
, it will trigger the trigger before any other browser action.
According to the documentation¹:
The keydown
event is triggered when a key is pressed down. Unlike the keypress
event, the keydown
event 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><inputid="txt_cep" />
Note: Chrome does not fire the keypress
event for known keyboard shortcuts ¹
Reference 1: link