I'm building an application, and would like to do an autocomplete within a textarea, much like how Twitter/Facebook does theirs with the @[name]. However, I would like to it trigger when I enter [TID:x], where x is an integer of any length.
It appears that Twitter/Facebook start their autocomplete after you hit the @ sign, and then sends the text data after it for the autocomplete. Does anyone have any idea if the jQuery UI plugin (or any other plugin) can do something like this?
This is indeed possible. You can tap into the autocomplete widget's events (search
and select
) to accomplish this:
var triggered = false;
var trigger = "TDI:";
$("input").autocomplete({
source: [...],
search: function() {
if (!triggered) {
return false;
}
},
select: function(event, ui) {
var text = this.value;
var pos = text.lastIndexOf(trigger);
this.value = text.substring(0, pos + trigger.length) +
ui.item.value;
triggered = false;
return false;
},
focus: function() { return false; },
minLength: 0
}).bind("keyup", function() {
var text = this.value;
var len = text.length;
var last;
var query;
var index;
if (triggered) {
index = text.lastIndexOf(trigger);
query = text.substring(index + trigger.length);
$(this).autocomplete("search", query);
}
else if (len >= trigger.length) {
last = text.substring(len - trigger.length);
triggered = (last === trigger);
}
});
Demo here: http://jsfiddle.net/andrewwhitaker/kCkga/
Notes:
I have created a plugin for that, which uses jQuery-UI Autocomplete and Andrew's example (thanks for that).
Url: https://github.com/experteer/autocompleteTrigger
Demo: http://jsfiddle.net/dmattes/2YRgW/1/
$('input,textarea').autocompleteTrigger({
triggerStart : '@',
triggerEnd: '',
source: [
"Asp",
"BASIC",
"COBOL",
"ColdFusion",
"Erlang",
"Fortran",
"Groovy",
"Java",
"JavaScript",
"Lisp",
"Perl",
"PHP",
"Python",
"Ruby",
"Scala",
"Scheme"
]
});
Best, Daniel
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With