Multi-word Autocomplete Search

by Julien Etienne

HTML

<div class="demo">
    <div class="ui-widget">
        <label for="tags">Multi-word search: </label>
        <input id="tags">
    </div>
</div>

CSS

.srchHilite {background: yellow;}

JavaScript

var availableTags = [
	"win the day",
	"win the heart of wi",
	"win the heart of someone win"
];

var autoCompNodeId = 'tags';

$("#" + autoCompNodeId).autocomplete({
  source : function(requestObj, responseFunc) {
    var matchArry = availableTags.slice(); //-- Copy the array
    var srchTerms = $.trim(requestObj.term).split(/\s+/);
    
    // For each search term, remove non-matches.
    $.each(srchTerms, function(J, term) {
      var regX = new RegExp(term, "i");
      matchArry = $.map(matchArry, function(item) {
        return regX.test(item) ? item : null;
      });
    });
    
    // Return the match results.
    responseFunc(matchArry);
  },
  open : function(event, ui) {
    
    /* This function provides no hooks to the results list; 
      so, we have to trust the selector, for now. */
    
    var resultsList = $("ul.ui-autocomplete > li.ui-menu-item > a");
    
    var srchTerm = $.trim(
      $("#" + autoCompNodeId).val()).split(/\s+/).join('|');
    
    // Loop through the results list and highlight the terms.
    resultsList.each(function() {
      var jThis = $(this);
      var regX = new RegExp('\\b' + srchTerm + '\\b', "ig");
      var oldTxt = jThis.text();
      
      jThis.html(
        oldTxt.replace(regX, '<span class="srchHilite">$1</span>'));
    });
  }
});