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??
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??
Share Improve this question edited Oct 22, 2019 at 15:24 Liam 29.8k28 gold badges139 silver badges203 bronze badges asked Apr 11, 2012 at 16:30 assaqqafassaqqaf 1,5854 gold badges22 silver badges39 bronze badges 2- There's a jQuery plugin to determine a browser's language setting. See this SO thread. Then you can figure out the keyboard code for the character you want in each langauge. – Belladonna Commented Apr 11, 2012 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 Commented Apr 11, 2012 at 19:29
2 Answers
Reset to default 7 +50To 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./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's approach is currently considered deprecated, as indicated in the official Mozilla documentation (https://developer.mozilla/en-US/docs/Web/API/UIEvent/which). Unfortunately, relying on it may not be the best choice.
A more modern and remended approach is to utilize the event.code
method to achieve the same result, specifically capturing the "KeyM" key press:
body.addEventListener("keydown", (e) => {
if (e.code === "KeyM") {
// The 'M' key has been pressed
}
})
By embracing this method, you ensure patibility and adhere to the latest best practices in web development.