Making jQuery UI Autocomplete “Super Search”

jQuery UI’s autocomplete widget provides no built in functionality to alter the search behavior, but has a static filter method that can be overridden instead, and as such, will be on an application wide basis. “Super search” is a generic term meaning orderless word search, as that “foo bar” and “bar foo” discover the same results. This code can go anytime after jQuery UI library is loaded. [code] $.extend($.ui.autocomplete, { filter: function(array, term) { if (term) { var regexes = $.Enumerable.From(RegExp.escape(term).split(” “)) .Select(function(t) { var regex = new RegExp([“.*?”, t, “.*?”].join(“”)); regex.compile(regex.source, “im”); return regex; }).ToArray(); return $.grep(array, function(value) { var testOn = value.label || value.value || value; return _(regexes).all(function(t) { return t.test(testOn); }); }); } else return array; } }); [/code] This code shamelessly uses some of my favorite libraries but could be easily crafted to work without them. linq.js underscore.js And also makes use of the following function: [code] RegExp.escape = function (text) { return text.replace(/[-[]{}()*+?.,\^$|#]/g, “\$&”); } [/code]

Leave a Reply

Your email address will not be published. Required fields are marked *

America's Best Software Engineers, On-Demand, at an Affordable Price
Surge Forward With Us