5

I have implemented an autocomplete using jquery-ui. I want to limit the number of items shown to 10 and each item custom formatted. Here is the code

$("#text1").autocomplete({
  minLength: 2,
  source: function (request, response) {
  var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i")
  , results = [];
  $.each(source, function (i, value) {
    if (matcher.test(value.value) && $.inArray(value.label, results) < 0) {
    results.push(value.label);
    }
   });

  response(results);
  }
 }).data("autocomplete")
      ._renderMenu = function(ul, items) {
        var self = this;
        $.each(items, function (index, item) {
            if (index < 10) {
              $.ui.autocomplete.prototype._renderItem = function(ul, item) {
                var re = new RegExp("^" + this.term, "i");
                var t = item.label.replace(re, "<span style='font-weight:bold;color: Blue;'>" + "$&" + "</span>");
                var listItem = $("<li></li>")
                               .data("item.autocomplete", item)
                               .append("<a>" + t + "</a>")
                               .appendTo(ul);
                return listItem;

              }
            }
            });
      };

This seems not to work as it is not throwing any result. Any help regarding this?

Ankit Garg
  • 709
  • 1
  • 11
  • 26

1 Answers1

5

I figured it out. Seems that I have to override both _renderMenu and _renderItem. It works now.

Ankit Garg
  • 709
  • 1
  • 11
  • 26
  • Hi Anit, I'm having a similar issue. Any chance you could post the working code? – Beetroot-Beetroot Jul 16 '13 at 00:51
  • 1
    @Beetroot-Beetroot You have override the _renderMenu and _renderItem. The code has been dug deep. But here is the reference which you can look into http://stackoverflow.com/questions/2435964/jqueryui-how-can-i-custom-format-the-autocomplete-plug-in-results – Ankit Garg Jul 16 '13 at 02:35
  • 1
    @Akit, thank you for your quick reply. In the meantime I got a result by calling `._renderItemData` from `._renderMenu` to reproduce the plugin's standard behaviour. This is appropriate in my case, since I want bog standard menu items but with separators to divide the menu into sections. Thanks again. – Beetroot-Beetroot Jul 16 '13 at 03:18
  • 1
    In 1.10.3 just `data('uiAutocomplete')._renderItem` – Sergey Oct 08 '13 at 17:22