Display an icon in jQuery UI autocomplete results
Asked Answered
A

1

10

I'm using the jQuery UI Autocomplete plugin (version 1.8), and I'd like to customize the way the suggestions show up. Specifically, I want to display not only some text, but an icon as well. However, when I send the <img> tag, it just gets rendered as plain text in the results list.

Is there some way to change this behavior? Alternatively, can you suggest a different way to include images in the returned results and have them show up in the suggestions?

Adelbert answered 22/9, 2010 at 23:19 Comment(0)
C
13

Taken from here

$("#search_input").autocomplete({source: "/search",
                                 minLength: 3,
                                 select: function (event, ui) {
                                     document.location = ui.item.url;
                                 }
})
.data("autocomplete")._renderItem = function (ul, item) {
//As per recent documemtation above line should be 
//.autocomplete( "instance" )._renderItem = function (ul, item) {
    return $('<li class="ui-menu-item-with-icon"></li>')
        .data("item.autocomplete", item)
        .append('<a><span class="' + item.type + '-item-icon"></span>' + item.label + '</a>')
        .appendTo(ul);
};

And the CSS:

.ui-menu .ui-menu-item-with-icon a {
  padding-left: 20px;
  
}
span.group-item-icon,
span.file-item-icon {
  display: inline-block;
  height: 16px;
  width: 16px;
  margin-left: -16px;
}
span.group-item-icon {
  background: url("/image/icons/group.png") no-repeat left 4px;
}
span.product-item-icon {
  background: url("/image/icons/product.png") no-repeat left 7px;
}
Conservatoire answered 12/10, 2010 at 12:4 Comment(2)
This works great, thanks! Since I wanted a different image for each item, I stuck an <img> tag directly into the <a> element rather than using CSS, but this is perfect.Adelbert
the example on jqueryui site is not working in chrome in January 2017Galenism

© 2022 - 2024 — McMap. All rights reserved.