Michael Low
Michael Low

Reputation: 24506

How to get the correct language and case for key press in JS event listener?

I have the following jQuery event listener to get the key pressed in a text box:

$("#theInput").keyup(function (e) {
    var charCode = e.keyCode || e.which;
    alert(charCode);
    /* rest of the code */
});

My problem is how to accurately get the code for the letter typed. For instance, if I press the a key it will alert '65' - regardless of whether it was a or A. If I switch the input language to a foreign language (e.g. Japanese, Chinese, Thai) and press the a key, it still returns '65' rather than a different code to let me know the foreign character.

Is there a way to I fix this so it gives the correct language and case of the letter?

Upvotes: 1

Views: 3180

Answers (2)

nnnnnn
nnnnnn

Reputation: 150080

Have you read the jQuery doco on how the keyup and keydown events work? They are supposed to return a key code (rather than a character code) without regard for whether shift was down at the time, though the event object does have a shiftKey property to tell you whether shift was down. keyup lets you distinguish between different keys associated with the same character, so you can tell whether a digit was entered via the numeric keypad or not.

The event you want is keypress, which returns a character code that differentiates between upper and lower case. Though having said that I'm not sure how it works for foreign languages, and in any case the whole approach doesn't allow for the user entering other text by pasting from the clipboard so that's something else you need to consider.

(By the way, jQuery normalises the event.which property so you shouldn't need to bother checking event.keyCode first.)

Upvotes: 7

Ricardo Tomasi
Ricardo Tomasi

Reputation: 35283

Keys are the same regardless of the language. You could get the case with .shiftKey, but the most reliable way is to save the actual characters:

$('#input').keyup(function(e){
  var character = this.value.slice(-1)
  console.log(character)
})

This is overly simplified, though, as text can be typed somewhere other than the end. You'd have to find the cursor position and then get the respective char.

Upvotes: -1

Related Questions