Search code examples
jqueryjquery-uijquery-pluginsjquery-ui-autocompletejquery-templates

Is there a way to use jQuery templates (official plugin) with jQuery UI Autocomplete?


I've found this "hack" to use jTemplates with the jQuery UI Autocomplete:

http://www.shawnmclean.com/blog/2011/02/using-jqueryui-autocomplete-with-jtemplates/

but, is there a way to use the official jQuery template plugin with jQuery UI Autocomplete? I would just use the demo in the link, but prefer a cleaner method if possible.

(It's necessary to use templates because I'm using them elsewhere in the site and would like to use the consistent layout for the autocomplete items without having to maintain two versions.)


Solution

  • OK, jQuery UI makes this extremely easy. From the demo on page http://jqueryui.com/demos/autocomplete/#custom-data, you can just alter the .data() call:

    //this is the original code in the demo
    .data( "autocomplete" )._renderItem = function( ul, item ) {
        return $( "<li></li>" )
            .data( "item.autocomplete", item )
            .append( "<a>" + item.label + "<br>" + item.desc + "</a>" )
            .appendTo( ul );
    };
    

    and replace it with this .data() call:

    .data( "autocomplete" )._renderItem = function( ul, item ) {
        return $( "#myTemplate" ).tmpl( item ).appendTo( ul );
    };
    
    // template
    <script id="myTemplate" type="text/x-jquery-tmpl">
        <li><a>${label}<br />${desc}</a></li>
    </script>
    

    and here's the working code in a fiddle: http://jsfiddle.net/swatkins/XXeDd/