2

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> 
1
  • Are you asking for a way to semantically search based on the search criteria or how to use the autocomplete to call a server url to get results and render the results? Commented Jun 21, 2012 at 23:22

1 Answer 1

1

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:

$(".text-search").autocomplete({ autoFocus: true, source: function(request, response) { var regexStr = "\\b(" + $.map($.trim(request.term).split(" "), function(term) { return $.ui.autocomplete.escapeRegex($.trim(term)) }).join("|") + ")\\b", matcher = new RegExp(regexStr); response($.grep(data, function(value) { return matcher.test(value.label || value.value || value); })); }, delay: 0, minLength: 2 }); 

The regular expression piece looks cryptic, but it's just generating an expression using alternation (|). For example, if you type brown cow, \b(brown|cow)\b is generated which will match any string with "brown" or "cow".

Example: http://jsfiddle.net/hTfj9/

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.