JQuery Autocomplete matching multiple unordered words in a string

I am trying to show the best match for the entered query. for instance

Now jQuery does not give me the desired effect. When I type: one today , autocomplete will not show anything, but if I type one day , it will show search results that start with these two words in that order. I want one today to show one day - the first and last today . I want the search results to show that they have those words in which order is not important. I looked over here and couldnโ€™t find anything like it, it seems like such a general search method that I donโ€™t see why no one asked this question. Is there a built-in method that handles this?

<!doctype html> <html lang="en"> <head> <meta charset="utf-8" /> <title>jQuery UI Autocomplete - Default functionality</title> <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" /> <script src="http://code.jquery.com/jquery-1.9.1.js"></script> <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script> <link rel="stylesheet" href="/resources/demos/style.css" /> <script> $(function() { var availableTags = [ "one day is the first and last today" , "tuesday is today" , "one" , "one day is tomorrow" ]; $( "#tags" ).autocomplete({ source: availableTags, multiple: true, mustMatch: false }); }); </script> </head> <body> <div class="ui-widget"> <label for="tags">Tags: </label> <input id="tags" /> </div> </body> </html> 
+6
source share
1 answer

Try to override the default filter logic provided by the completion.

 // Overrides the default autocomplete filter function to search for matched on atleast 1 word in each of the input term words $.ui.autocomplete.filter = function (array, terms) { arrayOfTerms = terms.split(" "); var term = $.map(arrayOfTerms, function (tm) { return $.ui.autocomplete.escapeRegex(tm); }).join('|'); var matcher = new RegExp("\\b" + term, "i"); return $.grep(array, function (value) { return matcher.test(value.label || value.value || value); }); }; 

Fiddle

Or create your own filter function and process the returned search query to keep the full filter function as is.

 function customFilter(array, terms) { arrayOfTerms = terms.split(" "); var term = $.map(arrayOfTerms, function (tm) { return $.ui.autocomplete.escapeRegex(tm); }).join('|'); var matcher = new RegExp("\\b" + term, "i"); return $.grep(array, function (value) { return matcher.test(value.label || value.value || value); }); }; $("#tags").autocomplete({ source: availableTags, multiple: true, mustMatch: false ,source: function (request, response) { response(customFilter( availableTags, request.term)); }, }); 

Fiddle

+10
source

Source: https://habr.com/ru/post/954904/


All Articles