Using HTML in jQuery UI autocomplete

Before jQuery UI 1.8.4 I could use HTML in the JSON array I built to work with an autocomplete.

I was able to do something like:

$row_array['label'] = '<span style="color: red; font-family: courier;">User, Name</span>';

That would show up as red text in the drop down.

As of 1.8.4 that does not work. I found http://dev.jqueryui.com/ticket/5275 which tells me to use the custom HTML example here which I have had no luck with.

How can I go about getting HTML to show up in the suggestion?

My jQuery is:

<script type="text/javascript">
    $(function() {
        $("#findUserIdDisplay").autocomplete({
            source: "ui_autocomplete_users_withuname.php",
            minLength: 2,
            select: function(event, ui) {
                $('#findUserId').val(ui.item.id);
            }
        });
    });
</script>

My JSON array includes HTML like the following:

[{"label":"<span style="color: red";>User, Name</span>","value":"User, Name","id":"10"}]

Answers


Add this to your code:

).data( "autocomplete" )._renderItem = function( ul, item ) {
            return $( "<li></li>" )
                .data( "item.autocomplete", item )
                .append( "<a>"+ item.label + "</a>" ) 
                .appendTo( ul );
        };

So your code becomes:

<script type="text/javascript">
 $(function () {
     $("#findUserIdDisplay").autocomplete({
         source: "ui_autocomplete_users_withuname.php",
         minLength: 2,
         select: function (event, ui) {
             $('#findUserId').val(ui.item.id);
             return false;
         }
     }).data("ui-autocomplete")._renderItem = function (ul, item) {
         return $("<li></li>")
             .data("item.autocomplete", item)
             .append("<a>" + item.label + "</a>")
             .appendTo(ul);
     };
 });
</script>

Note: On old versions of jQueryUI use .data("autocomplete")" instead of .data("ui-autocomplete")


This is also documented in jquery-ui autocomplete documentation at: http://api.jqueryui.com/autocomplete/#option-source

The trick is:

  1. Use this jQuery UI extension
  2. Then in autocomplete option pass autocomplete({ html:true});
  3. Now you can pass html &lt;div&gt;sample&lt;/div&gt; in "label" field of JSON output for autocomplete.

If you don't know how to add the plugin to JQuery UI then:

  1. Save the plugin(Scott González' html extension) in a js file or download the js file.
  2. You have already added the jquery-ui autocomplete script in your html page(or the jquery-ui js file). Add this plugin script after that autocomplete javascript file.

This solution is not recommended but you can just edit source file jquery.ui.autocomplete.js (v1.10.4)

Original:

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

Fixed:

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

I had the same issue, but I prefer to use a static array of options for my option('source') for performance. If you tried that with this solution, you'll find that jQuery searches on the entire label too.

EG if you supplied:

[{"label":"<span style="color: red";>User, Name</span>","value":"User, Name","id":"10"}]

Then typing "span" would match both results, to get it to search on the value only override the $.ui.autocomplete.filter function:

$.ui.autocomplete.filter = function(a,b){var g=new RegExp($.ui.autocomplete.escapeRegex(b),"i");return $.grep(a,function(c){return g.test(c.value||c)})}

You can edit the last parameter c.value to anything you want, e.g. c.id || c.label || c.value would allow you to search on label, value, or the id.

You can supply as many key/values to autocomplete's source parameter as you want.

PS: the original parameter is c.label||c.value||c.


I had the issue mentioned by Clarence. I needed to supply HTML to make a nice appearance with styles and images. This resulted in typing "div" matching all elements.

However, my value was only an ID number, so I couldn't allow the search to run off of just that. I needed the search to look for several values, not just the ID number.

My solution was to add a new field that held only the search values and check for that in the jQuery UI file. This is what I did:

(This is on jQuery UI 1.9.2; it may be the same on others.)

Edit filter function on line 6008:

filter: function (array, term) {
        var matcher = new RegExp($.ui.autocomplete.escapeRegex(term), "i");
        return $.grep(array, function (value) {
            if (value.searchonly == null)
                return matcher.test(value.label || value.value || value);
            else
                return matcher.test(value.searchonly);
        });
    }

I added the check for the "value.searchonly" field. If it is there, it uses that field only. If it is not there, it works as normal.

Then you use the autocomplete exactly as before, except you can add the "searchonly" key to your JSON object.

I hope that helps someone!


Need Your Help

Why do people consistently recommend using appConfig instead of using Settings files? (.NET)

.net .net-2.0 app-config appsettings application-settings

Very often I see the answer to the question like: "How should I store settings in my .NET app?" is to edit the app.config file by manually adding entries to the app.config (or web.config) like so:

c#: getter/setter

c# getter-setter

I saw something like the following somewhere, and was wondering what it meant. I know they are getters and setters, but want to know why the string Type is defined like this. Thanks for helping me.