Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery-ui-autocomplete - Overriding _renderMenu and _renderItem

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?

like image 405
Ankit Garg Avatar asked Aug 09 '12 07:08

Ankit Garg


1 Answers

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

like image 194
Ankit Garg Avatar answered Nov 07 '22 22:11

Ankit Garg