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

Categories

0 votes
630 views
in Technique[技术] by (71.8m points)

javascript - Get Correct keyCode for keypad(numpad) keys

I'm getting codes [96..105] by calling String.fromCharCode(event.keyCode) when pressing keys [0..9](digits) on the keypad. Though these codes correspond to characters: 'a b c d e f g h i' instead of [0..9].

Question:

I have 3 inputs in the form. User allowed to enter only in the 1-st input. While user press keys on keyboard some function need to filter it and write it to 2-nd input if pressed key is digit otherwise it must write it to the 3-rd input. How it can be corrected?

My implementation in JSFiddle

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

Use the keypress handler:

[somelement].onkeypress = function(e){
  e = e || event;
  console.log(String.fromCharCode(e.keyCode));
}

See also: this W3C testdocument

if you want to use the keyup or keydown handler, you can subtract 48 from e.keyCode to get the number (so String.fromCharCode(e.keyCode-48))


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...