How can I convert a character to its respective keycode?
For example:
a
to 65
b
to 66
As pointed out in the comments: the accepted answer is not correct, because it gives the character code and not the keyCode, which can be different, e.g. 'a'.charCodeAt(0) == 97
while the correct keyCode is 65
.
for converting just the standard characters from [a-zA-Z] or numbers [0-9] the code below can be used.
However this does not work correctly for any special keys like .
, Ö
, #
or whatsoever and I did not find a good solution for them. As a workaround one could use a site like http://keycode.info/ (which just captures the onkeydown
events and reads the event.keyCode
property).
function convertToKeyCode(target) {
var keyCode = target.value.toUpperCase().charCodeAt(0);
document.getElementById("keyCodeSpan").innerHTML = keyCode;
}
Keycode: