I need to add some functionality to the jQuery UI autosearch function. The problem I want to solve is to allow a user to enter text in any order that will search through a list of terms and display suggestions. For example, suppose I have the following terms:
the brown cow jumped over the moon
the blue cow watched in horror
the red cow simply laughed
the green cow got sick at such a sight
the yellow cow lost 5 bucks to the black cow
the black cow smiled at his fortune
If the user types in "the cow", I would expect the autocomplete feature to list all the results.
If I type in "brown moon", I would expect the first result to appear.
If I type in "fortune smiled", the last result would appear.
Basically this behavior allows the user to type in any string in any order and get search results.
Here’s what I’m thinking. I need to add a callback function in either the “open” or “search” events and manipulate the results there. Here’s my code so far:
$(function ()
{
var data =
[
"the brown cow jumped over the moon",
"the blue cow watched in horror",
"the red cow simply laughed ",
"the green cow got sick at such a sight",
"the yellow cow lost 5 bucks to the black cow",
"the black cow smiled at his fortune"
];
$(".text-search").autocomplete(
{
autoFocus: true,
source: data,
delay: 0,
minLength: 2,
open: function (e, ui)
{
debugger;
// what should i do here?
},
search: function (e, ui)
{
debugger;
// what should i do here?
}
});
});
<div class="ui-widget">
<label for="autocomplete">Autocomplete: </label>
<input class="text-search">
</div>
I would create your own regular expression based on the text the user entered. You can then use this regular expression to test each item in the candidate list:
The regular expression piece looks cryptic, but it’s just generating an expression using alternation (
|). For example, if you typebrown cow,\b(brown|cow)\bis generated which will match any string with “brown” or “cow”.Example: http://jsfiddle.net/hTfj9/