Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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");
    }
});
like image 387
Louis Tran Avatar asked Sep 16 '26 00:09

Louis Tran


1 Answers

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");
    }
});
like image 195
Rory McCrossan Avatar answered Sep 17 '26 13:09

Rory McCrossan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!