Detect printable keys
I need to detect whether the key which has just been pressed is a printable key, like a character, possibly accented, a number, a space, a punctuation symbol and so on, or a non printable key, like ENTER, TAB or DE开发者_Go百科LETE.
Is there a reliable way to do this in Javascript, other than listing all non printable keys and hope not to forget some?
Luckily, this task is much easier in modern browsers. You can now use KeyboardEvent.key
to detect a printable key via its length.
test.onkeydown = e => {
let isPrintableKey = e.key.length === 1;
alert(`Key '${e.key}' is printable: ${isPrintableKey}`);
}
<input id="test">
Besides that, you can also detect any other keys from the list, like Enter
, Delete
, Backspace
, Tab
, etc.
This method is much more reliable simply because unlike event.which
, event.key
is already standardized.
I answered a similar question yesterday. Note that you have to use the keypress
event for anything character-related; keydown
won't do.
I would argue that Enter is printable, by the way, and this function considers it to be. If you disagree, you can amend it to filter out keypresses with the which
or keyCode
property of the event set to 13.
function isCharacterKeyPress(evt) {
if (typeof evt.which == "undefined") {
// This is IE, which only fires keypress events for printable keys
return true;
} else if (typeof evt.which == "number" && evt.which > 0) {
// In other browsers except old versions of WebKit, evt.which is
// only greater than zero if the keypress is a printable key.
// We need to filter out backspace and ctrl/alt/meta key combinations
return !evt.ctrlKey && !evt.metaKey && !evt.altKey && evt.which != 8;
}
return false;
}
var input = document.getElementById("your_input_id");
input.onkeypress = function(evt) {
evt = evt || window.event;
if (isCharacterKeyPress(evt)) {
// Do your stuff here
alert("Character!");
}
});
If you need to identify printable key just for change detection as user change the input, you could use oninput
event.
let isPrintableKey = event.key.length === 1 || event.key === 'Unidentified';
If you do not include: || event.key === 'Unidentified'
your code will not work on mobile browsers.
精彩评论