LoginSignup
17
17

More than 5 years have passed since last update.

jQuery UIのAutocompleteのリストに画像を表示させる

Last updated at Posted at 2012-12-26

JavaScriptでオートコンプリート機能を実装する場合、
jQueryUIにAutocompleteという便利な機能があります。
http://jqueryui.com/autocomplete/

しかし、jQueryUIのAutocompleteで表示する候補リストは
テキストでしか表示できないようになっています。

なのでfacebookの友だち検索ような画像とテキストを組み合わせた
候補をリストで出すことは不可能です。
(htmlの文字列はエスケープされてしまう。)

そこでjQueryUIネイティブの_renderItem()関数を置き換えることで
htmlタグを利用できるようにします。

$.ui.autocomplete.prototype._renderItem = function( t, n) {
    return $( "<li></li>" )
        .data( "item.autocomplete", n )
        .append( $( "<a></a>" ).html( n.label ) )
        .appendTo( t );
};

 
 
元の関数はこんな感じでaタグで挟むところをtext()でなくhtml()を利用しています。

_renderItem: function(t, n) {
  return e("<li>").append(e("<a>").text(n.label)).appendTo(t)
}

サンプルHTML

<html>
  <head>
    <meta http-equiv="Content-type" content="text/html; charset=utf-8"/>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.2/jquery-ui.min.js"></script>
    <script type="text/javascript" charset="utf-8">
        jQuery(function($) {
            $.ui.autocomplete.prototype._renderItem = function(ul, item) {
                return $("<li></li>").data("item.autocomplete", item).append($("<a></a>").html(item.label)).appendTo(ul);
            };

            $('#widget').autocomplete({
                source : function(request, response) {
                    //なにかしらのRequest
                    $.getJSON(url, params, function(data) {
                        var list = [];
                        for (var key in data ) {
                            var item = data[key];
                            //labelにhtmlを設定
                            list.push({
                                label : "<img width=\"24\" height=\"24\" src=\"" + item.image + ".png\" \/><span class=\"username\">" + item.username + "<\/span>",
                                value : item.value
                            });
                        }
                        response(list);
                    });
                }
            });
        });
    </script>
  </head>
  <body id="body">
    <input type="text" id="widget" name="txt" />
  </body>
</html>
17
17
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
17
17