I'd like to make an autocomplete where if one types an "@" they are offered an autocomplete list of names.
I'm using jQueryUI autocomplete and the only problem with my solution ( http://jsfiddle.net/aUfrz/22/ ) is that the autocomplete-able text input needs to be placed on top of the textarea cursor position and not to the right as it currently stands.
Here's my JS that's in the JSFiddle:
$(document.body).on('keypress', 'textarea', function(e) {
var names = [
"johnny",
"susie",
"bobby",
"seth"
],
$this=$(this),
char = String.fromCharCode(e.which);
if(char == '@') {
console.log('@ sign pressed');
var input=$('<input style="position:relative; top:0px; left:0px;background:none;border:1px solid red" id="atSign" >');
$this.parent().append(input);
input.focus();
input.autocomplete({
source: names,
select: function (event, ui) {
console.log('value selected'+ui.item.value);
//$this.val('@'+ui.item.value);
$this.insertAtCaret(ui.item.value);
$this.focus();
input.remove();
} //select
}); //autocomplete
} //if
}); // keypress
HTML:
<textarea></textarea>
Please note that I have NOT shown here a jQuery plugin I used to insert the selected autocomplete suggestion at the caret position: insertAtCaret()
which I found at this other SO question.