How can I custom-format the Autocomplete plug-in results?

99,325

Solution 1

Autocomplete with live suggestion

Yes, you can if you monkey-patch autocomplete.

In the autocomplete widget included in v1.8rc3 of jQuery UI, the popup of suggestions is created in the _renderMenu function of the autocomplete widget. This function is defined like this:

_renderMenu: function( ul, items ) {
    var self = this;
    $.each( items, function( index, item ) {
        self._renderItem( ul, item );
    });
},

The _renderItem function is defined like this:

_renderItem: function( ul, item) {
    return $( "<li></li>" )
        .data( "item.autocomplete", item )
        .append( "<a>" + item.label + "</a>" )
        .appendTo( ul );
},

So what you need to do is replace that _renderItem fn with your own creation that produces the desired effect. This technique, redefining an internal function in a library, I have come to learn is called monkey-patching. Here's how I did it:

  function monkeyPatchAutocomplete() {

      // don't really need this, but in case I did, I could store it and chain
      var oldFn = $.ui.autocomplete.prototype._renderItem;

      $.ui.autocomplete.prototype._renderItem = function( ul, item) {
          var re = new RegExp("^" + this.term) ;
          var t = item.label.replace(re,"<span style='font-weight:bold;color:Blue;'>" + 
                  this.term + 
                  "</span>");
          return $( "<li></li>" )
              .data( "item.autocomplete", item )
              .append( "<a>" + t + "</a>" )
              .appendTo( ul );
      };
  }

Call that function once in $(document).ready(...) .

Now, this is a hack, because:

  • there's a regexp obj created for every item rendered in the list. That regexp obj ought to be re-used for all items.

  • there's no css class used for the formatting of the completed part. It's an inline style.
    This means if you had multiple autocompletes on the same page, they'd all get the same treatment. A css style would solve that.

...but it illustrates the main technique, and it works for your basic requirements.

alt text

updated working example: http://output.jsbin.com/qixaxinuhe


To preserve the case of the match strings, as opposed to using the case of the typed characters, use this line:

var t = item.label.replace(re,"<span style='font-weight:bold;color:Blue;'>" + 
          "$&" + 
          "</span>");

In other words, starting from the original code above, you just need to replace this.term with "$&".


EDIT
The above changes every autocomplete widget on the page. If you want to change only one, see this question:
How to patch *just one* instance of Autocomplete on a page?

Solution 2

this also works:

       $.ui.autocomplete.prototype._renderItem = function (ul, item) {
            item.label = item.label.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + $.ui.autocomplete.escapeRegex(this.term) + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "<strong>$1</strong>");
            return $("<li></li>")
                    .data("item.autocomplete", item)
                    .append("<a>" + item.label + "</a>")
                    .appendTo(ul);
        };

a combination of @Jörn Zaefferer and @Cheeso's responses.

Solution 3

Super helpful. Thank you. +1.

Here is a light version that sorts on "String must begin with the term":

function hackAutocomplete(){

    $.extend($.ui.autocomplete, {
        filter: function(array, term){
            var matcher = new RegExp("^" + term, "i");

            return $.grep(array, function(value){
                return matcher.test(value.label || value.value || value);
            });
        }
    });
}

hackAutocomplete();

Solution 4

Here it goes, a functional full example:

<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Autocomplete - jQuery</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css">
</head>
<body>
<form id="form1" name="form1" method="post" action="">
  <label for="search"></label>
  <input type="text" name="search" id="search" />
</form>

<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.2/jquery-ui.js"></script>
<script>
$(function(){

$.ui.autocomplete.prototype._renderItem = function (ul, item) {
    item.label = item.label.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + $.ui.autocomplete.escapeRegex(this.term) + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "<strong>$1</strong>");
    return $("<li></li>")
            .data("item.autocomplete", item)
            .append("<a>" + item.label + "</a>")
            .appendTo(ul);
};


var availableTags = [
    "JavaScript",
    "ActionScript",
    "C++",
    "Delphi",
    "Cobol",
    "Java",
    "Ruby",
    "Python",
    "Perl",
    "Groove",
    "Lisp",
    "Pascal",
    "Assembly",
    "Cliper",
];

$('#search').autocomplete({
    source: availableTags,
    minLength: 3
});


});
</script>
</body>
</html>

Hope this helps

Solution 5

jQueryUI 1.9.0 changes how _renderItem works.

The code below takes this change into consideration and also shows how I was doing highlight matching using Jörn Zaefferer's jQuery Autocomplete plugin. It will highlight all individual terms in the overall search term.

Since moving to using Knockout and jqAuto I found this a much easier way of styling the results.

function monkeyPatchAutocomplete() {
   $.ui.autocomplete.prototype._renderItem = function (ul, item) {

      // Escape any regex syntax inside this.term
      var cleanTerm = this.term.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');

      // Build pipe separated string of terms to highlight
      var keywords = $.trim(cleanTerm).replace('  ', ' ').split(' ').join('|');

      // Get the new label text to use with matched terms wrapped
      // in a span tag with a class to do the highlighting
      var re = new RegExp("(" + keywords + ")", "gi");
      var output = item.label.replace(re,  
         '<span class="ui-menu-item-highlight">$1</span>');

      return $("<li>")
         .append($("<a>").html(output))
         .appendTo(ul);
   };
};

$(function () {
   monkeyPatchAutocomplete();
});
Share:
99,325

Related videos on Youtube

dev.e.loper
Author by

dev.e.loper

Updated on September 07, 2020

Comments

  • dev.e.loper
    dev.e.loper over 3 years

    I’m using the jQuery UI Autocomplete plug-in. Is there a way to highlight search character sequence in drop-down results?

    For example, if I have “foo bar” as data and I type "foo" I’ll get “foo bar” in the drop-down, like this:

    “Breakfast” appears after “Bre” is typed with “Bre” having a bold type and “akfast” having a light one.

  • dev.e.loper
    dev.e.loper about 14 years
    yeah I'm aware of this plug in. however, we are using jQueryUI in our app so it would be nice to get this working with jQueryUI Autocomplete plug-in
  • dev.e.loper
    dev.e.loper about 14 years
    Thanks Cheeso. Do you have jsbin link for this?
  • shek
    shek over 13 years
    As of 2010-06-23, the jQuery Autocomplete plugin has been deprecated in favor of the jQuery UI Autocomplete plugin. See bassistance.de/jquery-plugins/jquery-plugin-autocomplete for more information
  • emanaton
    emanaton about 13 years
    Note that if you do chain things along, it's important to reset context: oldFn.apply(this, [ul, item]);
  • David Ryder
    David Ryder almost 13 years
    Thank you very much! Would be awesome if this became a part of jQuery UI.
  • David Ryder
    David Ryder almost 13 years
    One thing I would say is if you want it to bold the result in any part of the matched string (not just the beginning) modify the RegExp line to this: var re = new RegExp(this.term) ;
  • atp
    atp almost 13 years
    I liked this one better, as it matches the whole word.
  • Noel Abrahams
    Noel Abrahams over 12 years
    This is probably the best solution, but string.split is capable of only case-sensitive matches, I believe.
  • russau
    russau over 12 years
    Is this answer now out of date? JQ UI have a simple example for custom results here: jqueryui.com/demos/autocomplete/#custom-data
  • Cheeso
    Cheeso over 12 years
    @russau - no, I don't think it is out of date. I didn't see anything on that page regarding custom formatting of the results.
  • dreamerkumar
    dreamerkumar about 12 years
    Thanks Orolo, I was using autocomplete at multiple locations and wanted a central place where I can make the change to show only result that start with the typed characters and this one is what I exactly needed!
  • Kijana Woodard
    Kijana Woodard almost 12 years
    This works well. The only thing to look out for is that item.label is getting replaced. For me, I was getting "<strong..." in my text box. Just assigning the replace result to another variable cleared that up. You wouldn't have this problem if your data contains a value property that gets put into the text box.
  • Shmiddty
    Shmiddty over 11 years
    Wouldn't it be better to modify item.label and call the built in function passing the modified item object?
  • leopic
    leopic over 11 years
    If anyone is still looking into this, you don't need to tamper with the widget's original code, you can create a new custom widget that inherits from autocomplete and override the method there
  • George Mavritsakis
    George Mavritsakis over 11 years
    I think you are re-inventing the wheel! Why don't you use regular expressions which are faster, easier and more compact than all this code?
  • Lucky
    Lucky over 11 years
    the above with a scroll bar added into it....check this url jsbin.com/ezifi/569/edit
  • Patrick
    Patrick over 11 years
    Do you have any way to match words based on non-case-sensitive ? Because if I have a search "alfa", it will not highlight "Alfa"
  • Liron Harel
    Liron Harel over 11 years
    When I search with chars like '(' it causes an error ("Uncaught SyntaxError: Invalid regular expression: /(sam|at|()/: Unterminated group ") anyway to solve this by preventing collission with regex?
  • leora
    leora almost 11 years
    this doesn't work if you have an autocomplete that supports multiple values. any suggestions?
  • Aniket Kulkarni
    Aniket Kulkarni over 10 years
    Thanks. This is the best solution of all. It works for case insensitive.
  • Sam
    Sam about 10 years
    JQueryUI autocomplete appears to do a case insensitive search by default, so it makes sense to add the "i" flag in the RegExp object. There's also no reason to use the "^" in the regex as @DavidRyder mentioned. Like: var re = new RegExp(this.term, "i"); Great post!
  • Sam
    Sam about 10 years
    doesn't appear to anymore (as far as I can tell)
  • Sam
    Sam about 10 years
    Awesome answer! Love that it highlights the terms regardless of where they appear. Very cool. Thanks for updating the post. One question I did have is about the .ui-menu-item-highlight class you use. Is this expected to be defined by jquery-ui or by consumers? I changed the class name to suite my own means and simply made the font-weight bold. .jqAutocompleteMatch { font-weight: bold; }
  • Sam
    Sam about 10 years
    @IdanShechter Great comment. Some logic to escape the this.term for regex should be used before doing any processing. See Escape string for use in Javascript regex as one of many answers to how to do this.
  • adamst85
    adamst85 about 10 years
    The simplest way to get text highlighting in your autocomplete results. Obviously look out for the bugs as pointed out by leora and Kijana above
  • Illidan
    Illidan over 8 years
    In order to make it NOT case sensitive, add "gi" argument to Regular Expression: var re = new RegExp("^" + this.term, "gi");
  • zchrykng
    zchrykng about 8 years
    Generally it is better to spend time answering newer questions, or ones without answers rather than answering a question 6 years old that has already been answered.
  • Brian Leishman
    Brian Leishman over 4 years
    @RNKushwaha anywhere before you call to $().autocomplete()