Reputation: 35691
There is this jquery-autocomplete plugin which allows you to search for the exact string only..
So lets say this is the data..
[
['apple is good'],
['apple grows on tree'],
['the tree and the apple'],
['red apple'],
['apple tree']
]
Now searching for "apple" should show all.
But when typing "apple tree" it only returns back "apple tree".
I want it to return the smart results (2,3 and 5).
This means: it should re-evaluate the search again for each word (but filter it from the already filtered results)
This plugin allows you to provide your own search..
what can the refined search which will enable us to smartly search look like?
It needs to ignore whitespace and split the search query in to words to evaluate each word one after the other...
$("#textInputEle").autocomplete({
url:"path/to/data.json",
filter: function(result, filter) {
//whats should this function be?
}
});
Upvotes: 2
Views: 367
Reputation: 126042
You use the filter
option to supply your own filtering logic.
The function you supply takes result
and filter
parameters. The filter
parameter is what the user has searched for. The result
parameter is an item in the list of suggestions. Your function must return true
(if the suggestion is a match), or false
(if the suggestion is not a match).
The logic to do what you're trying to accomplish could look something like this:
result
you're passed by space (" "
) into an array of terms.That would look something like this:
$("#auto").autocomplete({
data: [
['apple is good'],
['apple grows on tree'],
['the tree and the apple'],
['red apple'],
['apple tree']
],
filter: function(result, filter) {
var terms = filter.split(" "),
match = true,
i = 0,
regex;
for (; match && i < terms.length; i++) {
regex = new RegExp(terms[i]);
match = match && regex.test(result.value);
}
return match;
}
});
Example: http://jsfiddle.net/ztkX2/1/
Upvotes: 1
Reputation: 8552
I believe the out-of-box functionality of jquery autocomplete will only return results that contain the phrase "apple tree". So, it would return #5 from your example, but it would also return true for phrases such as "He lives near an apple tree" and "The apple tree is the largest in her yard."
Upvotes: 1