[javascript] Get Character value from KeyCode in JavaScript... then trim

This is what I have now:

$("input").bind("keydown",function(e){
    var value = this.value + String.fromCharCode(e.keyCode);
}

If the e.keyCode may not be an ASCII character (Alt, backspace, del, arrows, etc.)... I would now need to trim these values from value somehow (preferably programmatically - not with lookup tables).

I'm using jQuery.

I must use the keydown event. keyPress doesn't activate for certain keys I need to capture (Esc, del, backspace, etc.).

I cannot use setTimeout to get the input's value. setTimeout(function(){},0) is too slow.

This question is related to javascript jquery special-characters keycode

The answer is


In my experience String.fromCharCode(e.keyCode) is unreliable. String.fromCharCode expects unicode charcodes as an argument; e.keyCode returns javascript keycodes. Javascript keycodes and unicode charcodes are not the same thing! In particular, the numberpad keys return a different keycode from the ordinary number keys (since they are different keys) while the same keycode is returned for both upper and lowercase letters (you pressed the same key in both cases), despite them having different charcodes.

For example, the ordinary number key 1 generates an event with keycode 49 while numberpad key 1 (with Numlock on) generates keycode 97. Used with String.fromCharCode we get the following:

String.fromCharCode(49) returns "1"
String.fromCharCode(97) returns "a"

String.fromCharCode expects unicode charcodes, not javascript keycodes. The key a generates an event with a keycode of 65, independentant of the case of the character it would generate (there is also a modifier for if the Shift key is pressed, etc. in the event). The character a has a unicode charcode of 61 while the character A has a charcode of 41 (according to, for example, http://www.utf8-chartable.de/). However, those are hex values, converting to decimal gives us a charcode of 65 for "A" and 97 for "a".[1] This is consistent with what we get from String.fromCharCode for these values.

My own requirement was limited to processing numbers and ordinary letters (accepting or rejecting depending on the position in the string) and letting control characters (F-keys, Ctrl-something) through. Thus I can check for the control characters, if it's not a control character I check against a range and only then do I need to get the actual character. Given I'm not worried about case (I change all letters to uppercase anyway) and have already limited the range of keycodes, I only have to worry about the numberpad keys. The following suffices for that:

String.fromCharCode((96 <= key && key <= 105)? key-48 : key)

More generally, a function to reliably return the character from a charcode would be great (maybe as a jQuery plugin), but I don't have time to write it just now. Sorry.

I'd also mention e.which (if you're using jQuery) which normalizes e.keyCode and e.charCode, so that you don't need to worry about what sort of key was pressed. The problem with combining it with String.fromCharCode remains.

[1] I was confused for a while -. all the docs say that String.fromCharCode expects a unicode charcode, while in practice it seemed to work for ASCII charcodes, but that was I think due to the need to convert to decimal from hex, combined with the fact that ASCII charcodes and unicode decimal charcodes overlap for ordinary latin letters.


Readable key names indexed by key code

There are relatively few key codes so I simply listed all the corresponding values in a static array so I could simply convert the number 65 into A using keyboardMap[65]

Not all key codes map to a printable character so some other identifiable string is returned.

You may need to modify the array to suit your needs and can simply return empty strings for all the characters you don't care to translate. The following array allows me to quickly and reliably determine which key was pressed in any environment. Enjoy!

// names of known key codes (0-255)

var keyboardMap = [
  "", // [0]
  "", // [1]
  "", // [2]
  "CANCEL", // [3]
  "", // [4]
  "", // [5]
  "HELP", // [6]
  "", // [7]
  "BACK_SPACE", // [8]
  "TAB", // [9]
  "", // [10]
  "", // [11]
  "CLEAR", // [12]
  "ENTER", // [13]
  "ENTER_SPECIAL", // [14]
  "", // [15]
  "SHIFT", // [16]
  "CONTROL", // [17]
  "ALT", // [18]
  "PAUSE", // [19]
  "CAPS_LOCK", // [20]
  "KANA", // [21]
  "EISU", // [22]
  "JUNJA", // [23]
  "FINAL", // [24]
  "HANJA", // [25]
  "", // [26]
  "ESCAPE", // [27]
  "CONVERT", // [28]
  "NONCONVERT", // [29]
  "ACCEPT", // [30]
  "MODECHANGE", // [31]
  "SPACE", // [32]
  "PAGE_UP", // [33]
  "PAGE_DOWN", // [34]
  "END", // [35]
  "HOME", // [36]
  "LEFT", // [37]
  "UP", // [38]
  "RIGHT", // [39]
  "DOWN", // [40]
  "SELECT", // [41]
  "PRINT", // [42]
  "EXECUTE", // [43]
  "PRINTSCREEN", // [44]
  "INSERT", // [45]
  "DELETE", // [46]
  "", // [47]
  "0", // [48]
  "1", // [49]
  "2", // [50]
  "3", // [51]
  "4", // [52]
  "5", // [53]
  "6", // [54]
  "7", // [55]
  "8", // [56]
  "9", // [57]
  "COLON", // [58]
  "SEMICOLON", // [59]
  "LESS_THAN", // [60]
  "EQUALS", // [61]
  "GREATER_THAN", // [62]
  "QUESTION_MARK", // [63]
  "AT", // [64]
  "A", // [65]
  "B", // [66]
  "C", // [67]
  "D", // [68]
  "E", // [69]
  "F", // [70]
  "G", // [71]
  "H", // [72]
  "I", // [73]
  "J", // [74]
  "K", // [75]
  "L", // [76]
  "M", // [77]
  "N", // [78]
  "O", // [79]
  "P", // [80]
  "Q", // [81]
  "R", // [82]
  "S", // [83]
  "T", // [84]
  "U", // [85]
  "V", // [86]
  "W", // [87]
  "X", // [88]
  "Y", // [89]
  "Z", // [90]
  "OS_KEY", // [91] Windows Key (Windows) or Command Key (Mac)
  "", // [92]
  "CONTEXT_MENU", // [93]
  "", // [94]
  "SLEEP", // [95]
  "NUMPAD0", // [96]
  "NUMPAD1", // [97]
  "NUMPAD2", // [98]
  "NUMPAD3", // [99]
  "NUMPAD4", // [100]
  "NUMPAD5", // [101]
  "NUMPAD6", // [102]
  "NUMPAD7", // [103]
  "NUMPAD8", // [104]
  "NUMPAD9", // [105]
  "MULTIPLY", // [106]
  "ADD", // [107]
  "SEPARATOR", // [108]
  "SUBTRACT", // [109]
  "DECIMAL", // [110]
  "DIVIDE", // [111]
  "F1", // [112]
  "F2", // [113]
  "F3", // [114]
  "F4", // [115]
  "F5", // [116]
  "F6", // [117]
  "F7", // [118]
  "F8", // [119]
  "F9", // [120]
  "F10", // [121]
  "F11", // [122]
  "F12", // [123]
  "F13", // [124]
  "F14", // [125]
  "F15", // [126]
  "F16", // [127]
  "F17", // [128]
  "F18", // [129]
  "F19", // [130]
  "F20", // [131]
  "F21", // [132]
  "F22", // [133]
  "F23", // [134]
  "F24", // [135]
  "", // [136]
  "", // [137]
  "", // [138]
  "", // [139]
  "", // [140]
  "", // [141]
  "", // [142]
  "", // [143]
  "NUM_LOCK", // [144]
  "SCROLL_LOCK", // [145]
  "WIN_OEM_FJ_JISHO", // [146]
  "WIN_OEM_FJ_MASSHOU", // [147]
  "WIN_OEM_FJ_TOUROKU", // [148]
  "WIN_OEM_FJ_LOYA", // [149]
  "WIN_OEM_FJ_ROYA", // [150]
  "", // [151]
  "", // [152]
  "", // [153]
  "", // [154]
  "", // [155]
  "", // [156]
  "", // [157]
  "", // [158]
  "", // [159]
  "CIRCUMFLEX", // [160]
  "EXCLAMATION", // [161]
  "DOUBLE_QUOTE", // [162]
  "HASH", // [163]
  "DOLLAR", // [164]
  "PERCENT", // [165]
  "AMPERSAND", // [166]
  "UNDERSCORE", // [167]
  "OPEN_PAREN", // [168]
  "CLOSE_PAREN", // [169]
  "ASTERISK", // [170]
  "PLUS", // [171]
  "PIPE", // [172]
  "HYPHEN_MINUS", // [173]
  "OPEN_CURLY_BRACKET", // [174]
  "CLOSE_CURLY_BRACKET", // [175]
  "TILDE", // [176]
  "", // [177]
  "", // [178]
  "", // [179]
  "", // [180]
  "VOLUME_MUTE", // [181]
  "VOLUME_DOWN", // [182]
  "VOLUME_UP", // [183]
  "", // [184]
  "", // [185]
  "SEMICOLON", // [186]
  "EQUALS", // [187]
  "COMMA", // [188]
  "MINUS", // [189]
  "PERIOD", // [190]
  "SLASH", // [191]
  "BACK_QUOTE", // [192]
  "", // [193]
  "", // [194]
  "", // [195]
  "", // [196]
  "", // [197]
  "", // [198]
  "", // [199]
  "", // [200]
  "", // [201]
  "", // [202]
  "", // [203]
  "", // [204]
  "", // [205]
  "", // [206]
  "", // [207]
  "", // [208]
  "", // [209]
  "", // [210]
  "", // [211]
  "", // [212]
  "", // [213]
  "", // [214]
  "", // [215]
  "", // [216]
  "", // [217]
  "", // [218]
  "OPEN_BRACKET", // [219]
  "BACK_SLASH", // [220]
  "CLOSE_BRACKET", // [221]
  "QUOTE", // [222]
  "", // [223]
  "META", // [224]
  "ALTGR", // [225]
  "", // [226]
  "WIN_ICO_HELP", // [227]
  "WIN_ICO_00", // [228]
  "", // [229]
  "WIN_ICO_CLEAR", // [230]
  "", // [231]
  "", // [232]
  "WIN_OEM_RESET", // [233]
  "WIN_OEM_JUMP", // [234]
  "WIN_OEM_PA1", // [235]
  "WIN_OEM_PA2", // [236]
  "WIN_OEM_PA3", // [237]
  "WIN_OEM_WSCTRL", // [238]
  "WIN_OEM_CUSEL", // [239]
  "WIN_OEM_ATTN", // [240]
  "WIN_OEM_FINISH", // [241]
  "WIN_OEM_COPY", // [242]
  "WIN_OEM_AUTO", // [243]
  "WIN_OEM_ENLW", // [244]
  "WIN_OEM_BACKTAB", // [245]
  "ATTN", // [246]
  "CRSEL", // [247]
  "EXSEL", // [248]
  "EREOF", // [249]
  "PLAY", // [250]
  "ZOOM", // [251]
  "", // [252]
  "PA1", // [253]
  "WIN_OEM_CLEAR", // [254]
  "" // [255]
];

Note: The position of each value in the array above is important. The "" are placeholders for codes with unknown values.

Try the following code snippet using this static array lookup approach...

_x000D_
_x000D_
var keyCodes = [];_x000D_
_x000D_
$("#reset").click(function() {_x000D_
  keyCodes = [];_x000D_
  $("#in").val("");_x000D_
  $("#key-codes").html("var keyCodes = [ ];");_x000D_
  $("#key-names").html("var keyNames = [ ];");_x000D_
});_x000D_
_x000D_
$(document).keydown(function(e) {_x000D_
  keyCodes.push(e.which);_x000D_
  updateOutput();_x000D_
});_x000D_
_x000D_
function updateOutput() {_x000D_
  var kC = "var keyCodes = [ ";_x000D_
  var kN = "var keyNames = [ ";_x000D_
_x000D_
  var len = keyCodes.length;_x000D_
_x000D_
  for (var i = 0; i < len; i++) {_x000D_
    kC += keyCodes[i];_x000D_
    kN += "'"+keyboardMap[keyCodes[i]]+"'";_x000D_
    if (i !== (len - 1)) {_x000D_
      kC += ", ";_x000D_
      kN += ", ";_x000D_
    }_x000D_
  }_x000D_
_x000D_
  kC += " ];";_x000D_
  kN += " ];";_x000D_
_x000D_
  $("#key-codes").html(kC);_x000D_
  $("#key-names").html(kN);_x000D_
}_x000D_
_x000D_
_x000D_
_x000D_
var keyboardMap = [_x000D_
  "", // [0]_x000D_
  "", // [1]_x000D_
  "", // [2]_x000D_
  "CANCEL", // [3]_x000D_
  "", // [4]_x000D_
  "", // [5]_x000D_
  "HELP", // [6]_x000D_
  "", // [7]_x000D_
  "BACK_SPACE", // [8]_x000D_
  "TAB", // [9]_x000D_
  "", // [10]_x000D_
  "", // [11]_x000D_
  "CLEAR", // [12]_x000D_
  "ENTER", // [13]_x000D_
  "ENTER_SPECIAL", // [14]_x000D_
  "", // [15]_x000D_
  "SHIFT", // [16]_x000D_
  "CONTROL", // [17]_x000D_
  "ALT", // [18]_x000D_
  "PAUSE", // [19]_x000D_
  "CAPS_LOCK", // [20]_x000D_
  "KANA", // [21]_x000D_
  "EISU", // [22]_x000D_
  "JUNJA", // [23]_x000D_
  "FINAL", // [24]_x000D_
  "HANJA", // [25]_x000D_
  "", // [26]_x000D_
  "ESCAPE", // [27]_x000D_
  "CONVERT", // [28]_x000D_
  "NONCONVERT", // [29]_x000D_
  "ACCEPT", // [30]_x000D_
  "MODECHANGE", // [31]_x000D_
  "SPACE", // [32]_x000D_
  "PAGE_UP", // [33]_x000D_
  "PAGE_DOWN", // [34]_x000D_
  "END", // [35]_x000D_
  "HOME", // [36]_x000D_
  "LEFT", // [37]_x000D_
  "UP", // [38]_x000D_
  "RIGHT", // [39]_x000D_
  "DOWN", // [40]_x000D_
  "SELECT", // [41]_x000D_
  "PRINT", // [42]_x000D_
  "EXECUTE", // [43]_x000D_
  "PRINTSCREEN", // [44]_x000D_
  "INSERT", // [45]_x000D_
  "DELETE", // [46]_x000D_
  "", // [47]_x000D_
  "0", // [48]_x000D_
  "1", // [49]_x000D_
  "2", // [50]_x000D_
  "3", // [51]_x000D_
  "4", // [52]_x000D_
  "5", // [53]_x000D_
  "6", // [54]_x000D_
  "7", // [55]_x000D_
  "8", // [56]_x000D_
  "9", // [57]_x000D_
  "COLON", // [58]_x000D_
  "SEMICOLON", // [59]_x000D_
  "LESS_THAN", // [60]_x000D_
  "EQUALS", // [61]_x000D_
  "GREATER_THAN", // [62]_x000D_
  "QUESTION_MARK", // [63]_x000D_
  "AT", // [64]_x000D_
  "A", // [65]_x000D_
  "B", // [66]_x000D_
  "C", // [67]_x000D_
  "D", // [68]_x000D_
  "E", // [69]_x000D_
  "F", // [70]_x000D_
  "G", // [71]_x000D_
  "H", // [72]_x000D_
  "I", // [73]_x000D_
  "J", // [74]_x000D_
  "K", // [75]_x000D_
  "L", // [76]_x000D_
  "M", // [77]_x000D_
  "N", // [78]_x000D_
  "O", // [79]_x000D_
  "P", // [80]_x000D_
  "Q", // [81]_x000D_
  "R", // [82]_x000D_
  "S", // [83]_x000D_
  "T", // [84]_x000D_
  "U", // [85]_x000D_
  "V", // [86]_x000D_
  "W", // [87]_x000D_
  "X", // [88]_x000D_
  "Y", // [89]_x000D_
  "Z", // [90]_x000D_
  "OS_KEY", // [91] Windows Key (Windows) or Command Key (Mac)_x000D_
  "", // [92]_x000D_
  "CONTEXT_MENU", // [93]_x000D_
  "", // [94]_x000D_
  "SLEEP", // [95]_x000D_
  "NUMPAD0", // [96]_x000D_
  "NUMPAD1", // [97]_x000D_
  "NUMPAD2", // [98]_x000D_
  "NUMPAD3", // [99]_x000D_
  "NUMPAD4", // [100]_x000D_
  "NUMPAD5", // [101]_x000D_
  "NUMPAD6", // [102]_x000D_
  "NUMPAD7", // [103]_x000D_
  "NUMPAD8", // [104]_x000D_
  "NUMPAD9", // [105]_x000D_
  "MULTIPLY", // [106]_x000D_
  "ADD", // [107]_x000D_
  "SEPARATOR", // [108]_x000D_
  "SUBTRACT", // [109]_x000D_
  "DECIMAL", // [110]_x000D_
  "DIVIDE", // [111]_x000D_
  "F1", // [112]_x000D_
  "F2", // [113]_x000D_
  "F3", // [114]_x000D_
  "F4", // [115]_x000D_
  "F5", // [116]_x000D_
  "F6", // [117]_x000D_
  "F7", // [118]_x000D_
  "F8", // [119]_x000D_
  "F9", // [120]_x000D_
  "F10", // [121]_x000D_
  "F11", // [122]_x000D_
  "F12", // [123]_x000D_
  "F13", // [124]_x000D_
  "F14", // [125]_x000D_
  "F15", // [126]_x000D_
  "F16", // [127]_x000D_
  "F17", // [128]_x000D_
  "F18", // [129]_x000D_
  "F19", // [130]_x000D_
  "F20", // [131]_x000D_
  "F21", // [132]_x000D_
  "F22", // [133]_x000D_
  "F23", // [134]_x000D_
  "F24", // [135]_x000D_
  "", // [136]_x000D_
  "", // [137]_x000D_
  "", // [138]_x000D_
  "", // [139]_x000D_
  "", // [140]_x000D_
  "", // [141]_x000D_
  "", // [142]_x000D_
  "", // [143]_x000D_
  "NUM_LOCK", // [144]_x000D_
  "SCROLL_LOCK", // [145]_x000D_
  "WIN_OEM_FJ_JISHO", // [146]_x000D_
  "WIN_OEM_FJ_MASSHOU", // [147]_x000D_
  "WIN_OEM_FJ_TOUROKU", // [148]_x000D_
  "WIN_OEM_FJ_LOYA", // [149]_x000D_
  "WIN_OEM_FJ_ROYA", // [150]_x000D_
  "", // [151]_x000D_
  "", // [152]_x000D_
  "", // [153]_x000D_
  "", // [154]_x000D_
  "", // [155]_x000D_
  "", // [156]_x000D_
  "", // [157]_x000D_
  "", // [158]_x000D_
  "", // [159]_x000D_
  "CIRCUMFLEX", // [160]_x000D_
  "EXCLAMATION", // [161]_x000D_
  "DOUBLE_QUOTE", // [162]_x000D_
  "HASH", // [163]_x000D_
  "DOLLAR", // [164]_x000D_
  "PERCENT", // [165]_x000D_
  "AMPERSAND", // [166]_x000D_
  "UNDERSCORE", // [167]_x000D_
  "OPEN_PAREN", // [168]_x000D_
  "CLOSE_PAREN", // [169]_x000D_
  "ASTERISK", // [170]_x000D_
  "PLUS", // [171]_x000D_
  "PIPE", // [172]_x000D_
  "HYPHEN_MINUS", // [173]_x000D_
  "OPEN_CURLY_BRACKET", // [174]_x000D_
  "CLOSE_CURLY_BRACKET", // [175]_x000D_
  "TILDE", // [176]_x000D_
  "", // [177]_x000D_
  "", // [178]_x000D_
  "", // [179]_x000D_
  "", // [180]_x000D_
  "VOLUME_MUTE", // [181]_x000D_
  "VOLUME_DOWN", // [182]_x000D_
  "VOLUME_UP", // [183]_x000D_
  "", // [184]_x000D_
  "", // [185]_x000D_
  "SEMICOLON", // [186]_x000D_
  "EQUALS", // [187]_x000D_
  "COMMA", // [188]_x000D_
  "MINUS", // [189]_x000D_
  "PERIOD", // [190]_x000D_
  "SLASH", // [191]_x000D_
  "BACK_QUOTE", // [192]_x000D_
  "", // [193]_x000D_
  "", // [194]_x000D_
  "", // [195]_x000D_
  "", // [196]_x000D_
  "", // [197]_x000D_
  "", // [198]_x000D_
  "", // [199]_x000D_
  "", // [200]_x000D_
  "", // [201]_x000D_
  "", // [202]_x000D_
  "", // [203]_x000D_
  "", // [204]_x000D_
  "", // [205]_x000D_
  "", // [206]_x000D_
  "", // [207]_x000D_
  "", // [208]_x000D_
  "", // [209]_x000D_
  "", // [210]_x000D_
  "", // [211]_x000D_
  "", // [212]_x000D_
  "", // [213]_x000D_
  "", // [214]_x000D_
  "", // [215]_x000D_
  "", // [216]_x000D_
  "", // [217]_x000D_
  "", // [218]_x000D_
  "OPEN_BRACKET", // [219]_x000D_
  "BACK_SLASH", // [220]_x000D_
  "CLOSE_BRACKET", // [221]_x000D_
  "QUOTE", // [222]_x000D_
  "", // [223]_x000D_
  "META", // [224]_x000D_
  "ALTGR", // [225]_x000D_
  "", // [226]_x000D_
  "WIN_ICO_HELP", // [227]_x000D_
  "WIN_ICO_00", // [228]_x000D_
  "", // [229]_x000D_
  "WIN_ICO_CLEAR", // [230]_x000D_
  "", // [231]_x000D_
  "", // [232]_x000D_
  "WIN_OEM_RESET", // [233]_x000D_
  "WIN_OEM_JUMP", // [234]_x000D_
  "WIN_OEM_PA1", // [235]_x000D_
  "WIN_OEM_PA2", // [236]_x000D_
  "WIN_OEM_PA3", // [237]_x000D_
  "WIN_OEM_WSCTRL", // [238]_x000D_
  "WIN_OEM_CUSEL", // [239]_x000D_
  "WIN_OEM_ATTN", // [240]_x000D_
  "WIN_OEM_FINISH", // [241]_x000D_
  "WIN_OEM_COPY", // [242]_x000D_
  "WIN_OEM_AUTO", // [243]_x000D_
  "WIN_OEM_ENLW", // [244]_x000D_
  "WIN_OEM_BACKTAB", // [245]_x000D_
  "ATTN", // [246]_x000D_
  "CRSEL", // [247]_x000D_
  "EXSEL", // [248]_x000D_
  "EREOF", // [249]_x000D_
  "PLAY", // [250]_x000D_
  "ZOOM", // [251]_x000D_
  "", // [252]_x000D_
  "PA1", // [253]_x000D_
  "WIN_OEM_CLEAR", // [254]_x000D_
  "" // [255]_x000D_
];
_x000D_
#key-codes,_x000D_
#key-names {_x000D_
  font-family: courier, serif;_x000D_
  font-size: 1.2em;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<input id="in" placeholder="Type here..." />_x000D_
<button id="reset">Reset</button>_x000D_
<br/>_x000D_
<br/>_x000D_
<div id="key-codes">var keyCodes = [ ];</div>_x000D_
<div id="key-names">var keyNames = [ ];</div>
_x000D_
_x000D_
_x000D_


Key codes worth noting

Letters A-Z: (65-90)

keyboardMap[65];  // A
...
keyboardMap[90];  // Z

Digits 0-9: (48-57)

keyboardMap[48];  // 0
...
keyboardMap[57];  // 9

Number Pad 0-9: (96-105)

keyboardMap[96];   // NUMPAD0
...
keyboardMap[105];  // NUMPAD9

Arrow Keys: (37-40)

keyboardMap[37];  // LEFT
keyboardMap[38];  // UP
keyboardMap[39];  // RIGHT
keyboardMap[40];  // DOWN

Tab Key: (9)

keyboardMap[9];  // TAB

Enter Key: (13)

keyboardMap[13];  // ENTER

Spacebar Key: (32)

keyboardMap[32];  // SPACE

OS Specific Key (91) Windows Key (Windows) or Command Key (Mac)

keyboardMap[91];  // OS_KEY

Alt Key: (18)

keyboardMap[18];  // ALT

Control Key: (17)

keyboardMap[17];  // CONTROL

Shift Key: (16)

keyboardMap[16];  // SHIFT

Caps Lock Key: (20)

keyboardMap[20];  // CAPS_LOCK

I'm assuming this is for a game or for a fast-responding type of application hence the use of KEYDOWN than KEYPRESS.

Edit: Dang! I stand corrected (thank you Crescent Fresh and David): JQuery (or even rather the underlying DOM hosts) do not expose the detail of the WM_KEYDOWN and of other events. Rather they pre-digest this data and, in the case of keyDown even in JQuery, we get:

Note that these properties are the UniCode values.
Note, I wasn't able to find an authorititative reference to that in JQuery docs, but many reputable examples on the net refer to these two properties.

The following code, adapted from some java (not javascript) of mine, is therefore totally wrong...

The following will give you the "interesting" parts of the keycode:

  value = e.KeyCode;
  repeatCount = value & 0xFF;
  scanCode = (value >> 16) & 0xFF;  // note we take the "extended bit" deal w/ it later.
  wasDown = ((value & 0x4000) != 0);  // indicate key was readily down (auto-repeat)
  if (scanCode > 127)
      // deal with extended
  else
      // "regular" character

I recently wrote a module called keysight that translates keypress, keydown, and keyup events into characters and keys respectively.

Example:

 element.addEventListener("keydown", function(event) {
    var character = keysight(event).char
 })

Refer this link Get Keycode from key press and char value for any key code

$('input#inp').keyup(function(e){
   $(this).val(String.fromCharCode(e.keyCode)); 
   $('div#output').html('Keycode : ' + e.keyCode);  
});

Just an important note: the accepted answer above will not work correctly for keyCode >= 144, i.e. period, comma, dash, etc. For those you should use a more general algorithm:

let chrCode = keyCode - 48 * Math.floor(keyCode / 48);
let chr = String.fromCharCode((96 <= keyCode) ? chrCode: keyCode);

If you're curious as to why, this is apparently necessary because of the behavior of the built-in JS function String.fromCharCode(). For values of keyCode <= 96 it seems to map using the function:

chrCode = keyCode - 48 * Math.floor(keyCode / 48)

For values of keyCode > 96 it seems to map using the function:

chrCode = keyCode

If this seems like odd behavior then well..I agree. Sadly enough, it would be very far from the weirdest thing I've seen in the JS core.

_x000D_
_x000D_
document.onkeydown = function(e) {_x000D_
    let keyCode = e.keyCode;_x000D_
    let chrCode = keyCode - 48 * Math.floor(keyCode / 48);_x000D_
    let chr = String.fromCharCode((96 <= keyCode) ? chrCode: keyCode);_x000D_
    console.log(chr);_x000D_
};
_x000D_
<input type="text" placeholder="Focus and Type"/>
_x000D_
_x000D_
_x000D_


For those of you who came here looking for the actual Unicode character values for a keycode, like I did, here is a function for that. For instance, given the right arrow unicode keycode this will output the visible string \u001B\u005B\u0043

function toUnicode(theString) {
    var unicodeString = '';
    for (var i = 0; i < theString.length; i++) {
        var theUnicode = theString.charCodeAt(i).toString(16).toUpperCase();
        while (theUnicode.length < 4) {
            theUnicode = '0' + theUnicode;
        }
        theUnicode = '\\u' + theUnicode;
        unicodeString += theUnicode;
    }
    return unicodeString;
}

You can also use the read-only property key. It also respects special keys like shift etc. and is supported by IE9.

When a non-printable or special character is pressed, the value will be on of the defined key values like 'Shift' or 'Multiply'.

  • Keyboard     event.key
  • X             -> 'x'
  • Shift+X -> 'X'
  • F5            -> 'F5'

I know this is an old question, but I came across it today searching for a pre-packaged solution to this problem, and found nothing that really met my needs.

Here is a solution (English only) that correctly supports Upper Case (shifted), Lower Case, punctuation, number keypad, etc.

It also allows for simple and straight-forward identification of - and reaction to - non-printable keys, like ESC, Arrows, Function keys, etc.

https://jsfiddle.net/5hhu896g/1/

keyboardCharMap and keyboardNameMap are the key to making this work

Thanks to DaveAlger for saving me some typing - and much discovery! - by providing the Named Key Array.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to special-characters

How to use tick / checkmark symbol (?) instead of bullets in unordered list? HTML for the Pause symbol in audio and video control How to run mysql command on bash? Which characters need to be escaped when using Bash? Matching special characters and letters in regex jQuery: Check if special characters exists in string Checking if a character is a special character in Java How to display special characters in PHP How should I escape commas and speech marks in CSV files so they work in Excel? grep for special characters in Unix

Examples related to keycode

"A namespace cannot directly contain members such as fields or methods" Get the value of input text when enter key pressed What are the JavaScript KeyCodes? How to know if .keyup() is a character key (jQuery) Where can I find a list of Mac virtual key codes? Get Character value from KeyCode in JavaScript... then trim Where can I find a list of keyboard keycodes?