Using HTML in jQuery UI autocomplete
Asked Answered
H

5

85

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"}]
Hamulus answered 15/8, 2010 at 15:31 Comment(1)
I would also like this answered, I just came across the same problem.Geosynclinal
G
126

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")

Geosynclinal answered 16/8, 2010 at 4:34 Comment(6)
What does _renderItem do? Is that converting the HTML?Hamulus
forum.jquery.com/topic/using-html-in-autocomplete See the second post, it describes it all.Geosynclinal
On new versions of jQuery ui use .data("ui-autocomplete") not data("autocomplete")Blackjack
If you remove the <a> you will not be able to click/scroll the item.Hekate
when I select an item - I get the tags in my input field ... how can I avoid that?Martell
I had two search inputs with autocomplete and for some reason it didn't work for second in one call. So I had to separate like this $('#first').autocomplete(autocompleteSearchObj).data("ui-autocomplete")._renderItem = autocompleteSearchHTML; $('#second').autocomplete(autocompleteSearchObj).data("ui-autocomplete")._renderItem = autocompleteSearchHTML; Let me know if I did the correct thing.Eyewash
R
11

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.
Rhu answered 28/7, 2013 at 8:48 Comment(0)
I
2

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)},
Ichthyosaur answered 2/7, 2014 at 6:1 Comment(0)
I
0

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.

Iyeyasu answered 21/11, 2011 at 21:40 Comment(1)
FYI: You don't need this solution if you use AJAX as your source because you're responsible for filtering with the passed in search "term" anywaysIyeyasu
S
0

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!

Seismography answered 11/1, 2013 at 20:31 Comment(1)
@PeterMortensen I lol'd that you edited it to include a Wikipedia link to HTML.Dehiscence

© 2022 - 2024 — McMap. All rights reserved.