Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect entered character with JavaScript

I'd like to start an action (enabling autocomplete) when user types '@'. I have jQuery available.

Usually on a QWERTY keyboard, it is like this:

$('textarea').live('keydown', function(e) {
  if (e.which === 50) {
    console.log('@ has been entered.');
  }
});

However it does not work correctly on an AZERTY keyboard. The keyCode = 50 corresponds to the é~/2 key. To type '@' in AZERTY keyboard, it is AltGr + à@/0 key.

Edit: Autocomplete starts when @ is entered, and only after that. Example, when someone enters "Hello @" then it starts, however when he types "Hello @nothing else" the complete won't do anything. Example: http://mrkipling.github.com/jQuery-at-username/ (it works only on QWERTY keyboard).

like image 611
jcisio Avatar asked Aug 26 '12 21:08

jcisio


2 Answers

Use keypress instead of keydown. While keydown relates to every press of a key, keypress relates to the translated characters, so for example a can be different to a while the shift key is pressed, composed characters work, dead-keys work, and other differences in keyboard mappings are handled.

like image 121
Jon Hanna Avatar answered Sep 18 '22 13:09

Jon Hanna


How about checking if @ was entered as the last character in the field value?

$("body").on("keyup", "textarea", function(e) {
    if (this.value.indexOf("@") == this.value.length - 1) {
        console.log("Starting autocomplete");
    }
});​

DEMO: http://jsfiddle.net/FKhPW/2/

like image 25
VisioN Avatar answered Sep 21 '22 13:09

VisioN