Js: how to get a LOCALIZED character when a key is pressed?

I need to get a localized character on a keypress event. For example: on the Czech key block I need to get Ε™ not 5 characters (key code 53) (see Czech keyboard layout ). Is there any other way to get character and not use text input and reading value? In other words, is there a way to get a character from an event object in accordance with the current layout of the user's keyboard?


(added sample code)

<html> <body> <script language="JavaScript"> function onLoad() { console.log(document.getElementById("test")); document.getElementById("test").onkeydown = function(event) { console.log("Code: "+event.keyCode+"; Key: "+String.fromCharCode(event.keyCode)); } } </script> <body onLoad="onLoad();"> <input id="test"> </body> </html> 

( online example)

When you try this code and press Ε™-key, you will see in the Firebug console "Code: 53; Key: 5". And I need to get "Ε™" not "5".

I think this β€œproblem” appears on all non-English keyboards.

+7
source share
2 answers

Using the keypress event will give you the entered character, regardless of the keyboard layout.

 document.onkeypress = function(evt) { evt = evt || window.event; var charCode = evt.which || evt.keyCode; var charTyped = String.fromCharCode(charCode); alert("Character typed: " + charTyped); }; 

Here's my usual Jan Wolter link: a great page documenting JavaScript keyword processing: http://unixpapa.com/js/key.html

+15
source

And make sure you use keypress, but not the keydown event.

If you use "keydown" String.fromCharCode(event.keyCode || event.which) , it will not return you a localized character. At least this was a problem for me on OS X with Chrome / FF.

0
source

All Articles