Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery UI - Autocomplete - Custom style?

I'm using the following code and it's working, getting values back etc, but the <b> and <br> tags show up as text rather than get rendered. I'd like the item.id and item.label to be on different lines, if possible the item.id bold:

 $( "#predictSearch" ).autocomplete({
 source: function( request, response ) {
  $.ajax({
   url: "index.pl",
   dataType: "json",
   data: {
    term: request.term
   },
   success: function( data ) {
    response( $.map( data.items, function( item ) {
     return {
      label: '<B>' + item.id + '</B><br>' + item.label,
      value: item.id
     }
    }));
   }
  });
 },
 minLength: 2
});
like image 698
Raoul Avatar asked May 13 '11 12:05

Raoul


2 Answers

It seems like you have some extra code (ajax call) for the autocomplete that it may not need. But, you can just swap out the special characters that jquery puts in to escape the html in the 'open' event of the autocomplete.

$("#autocomplete_field").autocomplete({
source: "autocomplete.php",
minLength: 2,
open: function(event, ui){
       $("ul.ui-autocomplete li a").each(function(){
        var htmlString = $(this).html().replace(/&lt;/g, '<');
        htmlString = htmlString.replace(/&gt;/g, '>');
        $(this).html(htmlString);
        });
     }
});

Full example http://www.jensbits.com/2011/03/03/jquery-autocomplete-with-html-in-dropdown-selection-menu/.

And, if you are using perl in the autcomplete, http://www.jensbits.com/2011/05/09/jquery-ui-autocomplete-widget-with-perl-and-mysql/ is an example for that.

like image 85
jk. Avatar answered Oct 23 '22 19:10

jk.


Instead of Success event, use _renderItem event.

Live implementation at Vroom. Type airport, you shall notice an image at the left.

NOTE: _renderItem below has some complex calculation. Don't go by that, just utilize the idea.

$("#myInput")
        .autocomplete({
            minLength: 0,
            delay: 10,
            source: function (req, responseFn) {
                //Your ajax call here returning only responseFn Array having item.id and item.id
            },
            select: function (event, ui) {
                //action upon selecting an item
                return false;
            }
        })
    .data("autocomplete")
        ._renderItem = function (ul, item) {
            return $("<li></li>")
                .data("item.autocomplete", item)
                .append("<a><span class='airoplane'>" + (item[0] + (item[2] == "" ? "" : ", " + item[2]) + (item[1] == "" ? "" : " (" + item[1] + ")")).replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + $.ui.autocomplete.escapeRegex(this.term).replace(/([\^\$\(\)\[\]\{\}\*\.\+\?\|\\])/gi, "\\$1") + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "<span class='highlight'>$1</span>") + "</span></a>")
                .appendTo(ul);
        };
like image 28
iMatoria Avatar answered Oct 23 '22 21:10

iMatoria