JavaScript function to convert keyCodes into characters
javascript
Solution
You could use `String.fromCharCode()`
From MDN :
Syntax : `String.fromCharCode(num1, ..., numN)`
Parameters : `num1, ..., numN` (A sequence of numbers that are Unicode values.)
This method returns a string and not a String object.
Because fromCharCode is a static method of String, you always use it as String.fromCharCode(), rather than as a method of a String object you created.
Update:
Here I made a function that would do what you want : http://jsbin.com/ukukuq/2/
(Code)
function keyDownEvent(e) {
var other = {};
var output= {};
output['meta'] = {};
var html = '';
e = (e) ? e : ((event) ? event : null);
if (e) {
output['keyCode'] = (e.keyCode) ? e.keyCode : 'N/A';
output['charCode'] = (e.charCode) ? e.charCode : 'N/A';
output['meta']['shift'] = e.shiftKey ? true : false;
output['meta']['ctrl'] = e.ctrlKey ? true : false;
output['meta']['alt'] = e.altKey ? true : false;
output['meta']['meta'] = e.metaKey ? true : false;
html = document.getElementById('output')
return html.innerHTML += '<pre>keyDown : ' + JSON.stringify(output) + '</pre>';
} else {
return 'error';
}
}
function keyPressEvent(e) {
var other = {};
var output= {};
var html = '';
e = (e) ? e : ((event) ? event : null);
if (e) {
output['keyCode'] = (e.keyCode) ? e.keyCode : 'N/A';
output['charCode'] = (e.charCode) ? e.charCode : 'N/A';
html = document.getElementById('output')
return html.innerHTML += '<pre>keyPress : ' + JSON.stringify(output) + ' Character : <strong>' + String.fromCharCode(output['charCode']) + '</strong></pre><hr/>';
} else {
return 'error';
}
}
var test = document.getElementById('test');
test.onkeydown = keyDownEvent;
test.onkeypress = keyPressEvent;
Problem
Are there any built in functions in any JavaScript framework to convert keyCodes into characters? Which accounts the shift property, so it will return the correct characters. Or we just have to build our own function ?