JavaScript character detection

I would like to start an action (enable autocomplete) when the user enters "@". However, I do not know how to do it right. I have jQuery.

Usually on a QWERTY keyboard, it looks like this:

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

However, it does not work correctly on the AZERTY keyboard. KeyCode = 50 corresponds to a key é~/2. To enter "@" in the AZERTY keyboard, this is AltGr + à@/0.

Edit: I was not clean. Autofill begins when you type @, and only after that. For example, when someone enters “Hello @”, then he starts, but when he types “Hello @nothing else”, he won’t do anything. Example: http://mrkipling.github.com/jQuery-at-username/ (it only works on the QWERTY keyboard).

+5
source share
5 answers

Use keypressinstead keydown. While it keydownrelates to each keystroke, it keypressrefers to translated characters, therefore, for example, it amay differ from awhen the shift key is pressed, worked characters work, dead keys work, and other differences in keyboard mappings are processed.

+3
source

How about checking if it was @entered as the last character in a 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/

+2
source

, , - , .

var patt=new RegExp(/^@/);
var charCheck = setInterval(function(){
  if (patt.test($("#textInput").val())){
    // initiate autocomplete
  }
},100);

#textInput , @ . , test() true, .

0

: http://jsfiddle.net/LxpQQ/

:

jquery '@'

, :)

source: function(request, response) {
            if (request.term.indexOf("@") >= 0) {
                $("#loading").show();
                getTags(extractLast(request.term), function(data) {
                    response($.map(data.tags, function(el) {
                        return {
                            value: el.name,
                            count: el.count
                        }
                    }));
                    $("#loading").hide();                    
                });
            }
        },
0

event.key JS, @!

. .

const input = document.getElementById("textarea");
input.addEventListener("keydown", function (event) {
    if (event.key === "@") {
        // Do something
    }
});

Mozilla

0

All Articles