Reputation: 507
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).
Upvotes: 7
Views: 6864
Reputation: 113232
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.
Upvotes: 3
Reputation: 47089
event.key
and modern JS, checking for @
directly!No number codes anymore. You can check key directly.
const input = document.getElementById("textarea");
input.addEventListener("keydown", function (event) {
if (event.key === "@") {
// Do something
}
});
Upvotes: 2
Reputation: 34107
Here you go working demo: http://jsfiddle.net/LxpQQ/
From my old reply here:
Hope it will fit you cause :)
code
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();
});
}
},
Upvotes: 0
Reputation: 145368
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/
Upvotes: 2
Reputation: 47956
The only other option that comes to mind would be a timer that checks the content of the text input.
var patt=new RegExp(/^@/);
var charCheck = setInterval(function(){
if (patt.test($("#textInput").val())){
// initiate autocomplete
}
},100);
This code will inspect the contents of the #textInput
element and see if it matches the regular expression of a @
symbol at the beginning of the string. If it does, the test()
function will evaluate to true and you can initiate your autocomplete code.
Upvotes: 0