KEYCODE 9 JQUERY does not work

0

Hello

Can you tell me why keycode == 9 does not work?

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

Event e.which == 13 works, but e.keyCode == 9 does not.

    
asked by anonymous 01.02.2018 / 21:17

1 answer

1

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

    
01.02.2018 / 21:37