简体   繁体   中英

Jquery keypress() event doesn't catch Tab keycode

I want to do something if users press tab while they are typing on a textbox. But the code below can't handle tab button. I tried "13" for "Enter" and it worked but I'm not sure why it didn't work for Tab.

I think it might be because of the textbox losing focus when tab pressed. If this is the case, how can I prevent lossing focus when people press tab in this textbox?

Thank you.

$("#tagInpKey").keypress(function (e) {
    if (e.which == 9) {
       alert("Tab Pressed");
    }
});

From the documentation :

The keypress event is sent to an element when the browser registers keyboard input. This is similar to the keydown event, except that modifier and non-printing keys such as Shift, Esc, and delete trigger keydown events but not keypress events .

To fix this, use keydown instead:

$("#tagInpKey").keydown(function (e) {
    if (e.which == 9) {
       alert("Tab Pressed");
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM