KEYCODE 9 JQUERY does not work

Asked

Viewed 180 times

0

Hello!

Can you tell me why the event keycode == 9 doesn’t work?

$("#txt_cep").keypress(function (e) {
    if (e.keyCode == 9) {
        $("#btn_pesquisa_cep").click();
    } else if (e.which == 13) {
        $("#btn_pesquisa_cep").click();
    }
});

The event e.which == 13 works, but the e.keyCode == 9 nay.

1 answer

1


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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.