Jquery UI autocomplete - images IN the results overlay, not outside like the demo

风流意气都作罢 提交于 2019-11-29 04:52:30
Andrew Whitaker

The recommended way to change the display of list items in the suggestion list for autocomplete is to override the _renderItem method. Inside this method you must do several things:

  1. Append an li to the passed in ul. The li must include an a tag.
  2. Associate the proper data with that li
  3. Return that li.

Apart from this, you can perform any custom formatting logic you'd like. Here's how I would update your code:

$("input#autocomplete").autocomplete({
    delay: 10,
    minLength: 0,                                          
    source: updates,        
    select: function( event, ui ) {
        window.location.href = ui.item.value;
    }
}).data("autocomplete")._renderItem = function (ul, item) {
        return $("<li />")
            .data("item.autocomplete", item)
            .append("<a><img src='" + item.icon + "' />" + item.label + "</a>")
            .appendTo(ul);
}; 

As you can see, adding an img tag was as easy as placing it inside of the a tag mentioned above. Keep in mind you can also apply CSS rules to items that you add as well.

Here's a complete example that uses StackOverflow's API for searching users, and shows their avatars to the left of them.


Update: As of jQueryUI 1.10, you need to access widget data for autocomplete using .data("uiAutocomplete") (thanks for noticing the problem @Danny). With that in mind, here's an example working in 1.10:

$("input#autocomplete").autocomplete({
    delay: 10,
    minLength: 0,                                          
    source: updates,        
    select: function( event, ui ) {
        window.location.href = ui.item.value;
    }
}).data("uiAutocomplete")._renderItem = function (ul, item) {
        return $("<li />")
            .data("item.autocomplete", item)
            .append("<a><img src='" + item.icon + "' />" + item.label + "</a>")
            .appendTo(ul);
}; 

Example: http://jsfiddle.net/K5q5U/249/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!