Sunday, May 12, 2024
 Popular · Latest · Hot · Upcoming
50
rated 0 times [  53] [ 3]  / answers: 1 / hits: 42086  / 12 Years ago, mon, september 17, 2012, 12:00:00

I'd just like to know the range(s) of JavaScript keyCodes that correspond to typeable characters; or alternatively, the range of non-typeable (control) characters like backspace, escape, command, shift, etc. so I can ignore them.



The reason I ask is calling String.fromCharCode() is resulting in odd characters for control keys. For example I get [ for left command, % for left arrow. Weirdness like that.


More From » keycode

 Answers
5

Keydown will give you the keyCode of the key pressed, without any modifications.



$(#keypresser).keydown(function(e){
var keycode = e.keyCode;

var valid =
(keycode > 47 && keycode < 58) || // number keys
keycode == 32 || keycode == 13 || // spacebar & return key(s) (if you want to allow carriage returns)
(keycode > 64 && keycode < 91) || // letter keys
(keycode > 95 && keycode < 112) || // numpad keys
(keycode > 185 && keycode < 193) || // ;=,-./` (in order)
(keycode > 218 && keycode < 223); // []' (in order)

return valid;
});


Only the number keys, letter keys, and spacebar will have keycodes correlating to String.fromCharCode as it uses Unicode values.



Keypress will be the charCode representation of the text entered. Note that this event won't fire if no text is printed as a result of the keypress.



$(#keypresser).keypress(function(e){
var charcode = e.charCode;
var char = String.fromCharCode(charcode);
console.log(char);
});


http://jsfiddle.net/LZs2D/1/ Will demonstrate how these work.



KeyUp behaves similarly to KeyDown.


[#83042] Saturday, September 15, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
emiliano

Total Points: 381
Total Questions: 109
Total Answers: 93

Location: Jersey
Member since Fri, Oct 1, 2021
3 Years ago
emiliano questions
;