Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 DELETE.

Is there a reliable way to do this in Javascript, other than listing all non printable keys and hope not to forget some?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
275 views
Welcome To Ask or Share your Answers For Others

1 Answer

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">

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...