5

I use keydown event in jquery, but the problem it's stateless for input language. It's can't determine the input is in English language or in Hebrew or Arabic...? it returns only keycode, and I can't get character.

Is there any solution??

Liam
  • 27,717
  • 28
  • 128
  • 190
assaqqaf
  • 1,575
  • 4
  • 21
  • 38
  • There's a jQuery plugin to [determine a browser's language setting](https://github.com/dansingerman/jQuery-Browser-Language). See [this](http://stackoverflow.com/questions/1043339/javascript-for-detecting-browser-language-preference) SO thread. Then you can figure out the keyboard code for the character you want in each langauge. – Belladonna Apr 11 '12 at 17:04
  • I think the plugin is not solve the problem. the user can change language during typing. so, i cannt get the right char input by user. – assaqqaf Apr 11 '12 at 19:29

1 Answers1

7

To determine the actual character, you should use the keypress event instead of keydown. While keydown provides you with a key code, keypress indicates the character which was entered by the user.

Another difference is that when the user presses and holds a key, a keydown event is triggered only once, but separate keypress events are triggered for each inserted character.

Here's an example of using the keypress event:

<body>
<form>
  <input id="target" type="text" />
</form>

<script src="http://api.jquery.com/scripts/events.js"></script>
<script>
  $("#target").keypress(function(event) {
    var charCode = event.which; // charCode will contain the code of the character inputted
    var theChar = String.fromCharCode(charCode); // theChar will contain the actual character
  });
</script>
</body>
Dmytro Shevchenko
  • 33,431
  • 6
  • 51
  • 67
  • 1
    This worked for me. It picked up both Norwegian characters and then Arabic characters after changing the keyboard layout (while staying on the page - no reload inbetween). [Here's a jsFiddle](http://jsfiddle.net/wvywU/) – Simen Echholt Apr 13 '12 at 22:13