Reputation: 634
With reference to this question Sorting Autocomplete UI Results based on match location, there is a solution that provides for single value jQuery autocomplete but is it possible to get a similar solution for multiple values jQuery autocomplete (http://jqueryui.com/autocomplete/#multiple)?
Upvotes: 0
Views: 3107
Reputation: 126052
The only difference here is that you need to make sure and call extractLast
like the demo you linked to is doing. Here's the complete code that should work with multiple values (pay particular attention to the source
option):
$("#tags")
.on("keydown", function (event) {
if (event.keyCode === $.ui.keyCode.TAB && $(this).data("autocomplete").menu.active) {
event.preventDefault();
}
})
.autocomplete({
minLength: 0,
source: function (request, response) {
var term = $.ui.autocomplete.escapeRegex(extractLast(request.term))
// Create two regular expressions, one to find suggestions starting with the user's input:
, startsWithMatcher = new RegExp("^" + term, "i")
, startsWith = $.grep(source, function(value) {
return startsWithMatcher.test(value.label || value.value || value);
})
// ... And another to find suggestions that just contain the user's input:
, containsMatcher = new RegExp(term, "i")
, contains = $.grep(source, function (value) {
return $.inArray(value, startsWith) < 0 &&
containsMatcher.test(value.label || value.value || value);
});
// Supply the widget with an array containing the suggestions that start with the user's input,
// followed by those that just contain the user's input.
response(startsWith.concat(contains));
},
focus: function () {
return false;
},
select: function (event, ui) {
var terms = split(this.value);
terms.pop();
terms.push(ui.item.value);
terms.push("");
this.value = terms.join(", ");
return false;
}
});
Example: http://jsfiddle.net/Aa5nK/1/
Upvotes: 2
Reputation: 7362
In the response, you should return a list of result that match what you want in your query:
e.g.
list_of_terms = {"term0","term1","term2",...};
$("#inputsearch").autocomplete({
var term = request.term
var list = new Array();
source: function( request, response ) {
var cnt = 0;
$.each(list_of_terms, function(i) {
var rSearchTerm = new RegExp('^' + RegExp.quote(term),'i');
if (list_of_terms[i].match(rSearchTerm)) {
list[cnt] = list_of_terms[i];
cnt++;
}
});
response(list);
}
});
RegExp.quote = function(str) {
return (str+'').replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1");
};
provided i didn't miss a parenthesis, this should give you multiple values in your dropdown if the term entered equals the start of a term in your list_of_terms array
Upvotes: 0