Extension to jQuery autocomplete for multiple tag suggestion
The project I’m working on has fields that allow you to enter a series of tags. I wanted an autocomplete functionality for these, and looked at what’s already available using jQuery. I found the popular jq-autocomplete to be interesting, but it didn’t have the functionality out of the box. Yet it allowed for extension points in its options. I created custom functions to achieve the goal:
function lastWord (str) {
var words = str.split(" ");
return words[words.length - 1];
}
function customTemplate(str) {
return "<li>" + lastWord(str) + "</li>";
}
function customTextInsert(str, original) {
var firstWords = original.split(" ");
firstWords[firstWords.length - 1] = str;
var toReturn = firstWords.join(" ");
return toReturn;
}
function customTextInsertBinder(input) {
return function(str){ return customTextInsert(str, input.val()); }
}
function customTextMatch(typed) {
return this.match(new RegExp(lastWord(typed)));
}
Now, when I want to have a field autocompleted, I load the list of tags in a JavaScript array (here called “site_tags”), and I call:
$('#id_tags').autocomplete(
{list: site_tags,
match: customTextMatch,
insertText: customTextInsertBinder($("#id_tags")),
template: customTemplate});

Leave a comment