Why doesn’t it prevent undoing the focus change after pressing Tab-keypress?

I was messing around with preventDefault() and should be doing something wrong.

$("#input").bind("keypress", function(event) {
    if(event.which == 9) {
    event.preventDefault();
    alert("You pressed tab.");
    }
});

Tab functionality is not prevented. What is wrong with that?

+4
source share
3 answers

The event keypresssimply does not fire when Tab is pressed - this also explains why there is no warning, no matter what the default warning can prevent.

Changing the code to use keydownallows you to catch the tab and prevents the default focus from changing (in Chrome 1 anyway).

$("#input").bind("keydown", function(event) {
    if(event.which == 9) {
        event.preventDefault();
    }
});

1 Chrome 35 jQuery 1.6-2.1; KO 3.0.

+1

FIDDLE. . .

$("body").on("keydown", function(event) {
if(event.which == 9) {
event.preventDefault();
    alert("You pressed tab.");
}
});
+2

JQuery

: keypress - , , , , .

.on( "keypress", handler) ​​.trigger( "keypress" ) .

, . keydown, , , Shift, Esc delete , . .

, . .

+1

Source: https://habr.com/ru/post/1545902/


All Articles