I try to trigger a button when in an input field the return key has been hit. This works. But if I hit the tab key nothing is triggered because the TAB key event isn't captured.
Here is my JQ code snippet for example:
$("input[name=input]").on("keypress, keydown, keyup", function(e) {
var code = e.keyCode || e.which;
if ( code == 13 || code == 9 ) {
$("input[name=btn]").trigger("click");
}
});
I can't figure out how to get the tab key stroke working like a return key stroke.
- Use
Event.preventDefault()
to prevent the browser switching focus on Tab press. - Listen for
"keydown"
event only - Use KeyboardEvent.key instead
JavaScript's which and keyCode are deprecated, historically they both become a mess.
Even if jQuery normalizes with jQueryEvent.which
for both Event.keyCode
and Event.which
crossbrowser, I think we should abandon the two and use the more human friendly Event.key
. What makes more sense, 9
or 'Tab'
? 13
or 'Enter'
? 42
or... what is 42 anyways
$('input[name=input]').on('keydown', function(evt) {
if (evt.key === 'Tab' || evt.key === 'Enter') {
evt.preventDefault();
$('input[name=btn]').trigger('click');
}
});
- Only bind the
keydown
event. return false
andpreventDefault
on tab key so the focus is not lost.
Demo: http://jsfiddle.net/a08t4o7r/3/
$("input[name=input]").on("keydown", function(e) {
var code = e.keyCode || e.which;
if ( code == 13 || code == 9 ) {
e.preventDefault();
$("input[name=btn]").trigger("click");
return false;
}
});
来源:https://stackoverflow.com/questions/28084191/how-to-get-the-key-tab-event-on-an-input-element