jmhajek jmhajek - 1 year ago 93
Javascript Question

Displaying JQuery UI autocomplete as a table

I am using JQuery UI's autocomplete. I have a number of values, as well as a small collection of keywords, one of which is assigned to each value. I would like to display each pair in a mini-table, with the keyword in one cell and the value in the other. To do this, I am overwriting

, as mentioned in the documentation. However, when I do this, clicking on a value (or a keyword) doesn't actually do anything, so I cannot select any values. I suspect it has something to do with
data("item.autocomplete", item)
not being in the right place. Or maybe I need to overwrite some other function higher up (

$( "#tags" ).autocomplete({
source: getItems
.data( "autocomplete" )._renderItem = function( ul, item ) {
return $( '<table></table>' )
.data( "item.autocomplete", item )
.append( '<tr><td>' + item.keyword + '</td><td> ' + item.value + "</td></tr>" )
.appendTo( ul );

Answer Source

I think this can help you,here is the js:

$(function() {
//overriding jquery-ui.autocomplete .js functions
$.ui.autocomplete.prototype._renderMenu = function(ul, items) {
  var self = this;
  //table definitions
  $.each( items, function( index, item ) {
    self._renderItemData(ul, ul.find("table tbody"), item );
$.ui.autocomplete.prototype._renderItemData = function(ul,table, item) {
  return this._renderItem( table, item ).data( "ui-autocomplete-item", item );
$.ui.autocomplete.prototype._renderItem = function(table, item) {
  return $( "<tr class='ui-menu-item' role='presentation'></tr>" )
    .data( "item.autocomplete", item )
    .append( "<td >""</td>"+"<td>"+item.value+"</td>"+"<td>"+item.cp+"</td>" )
    .appendTo( table );
//random json values
var projects = [
    {id:78,value:"Santa Maria",cp:787},
$( "#project" ).autocomplete({
    minLength: 1,
    source: projects,
    //you can write for select too
    focus: function( event, ui ) {
        $( "#project" ).val( ui.item.value );
        $( "#project-id" ).val( );
        $( "#project-description" ).html( ui.item.cp );
        return false;

You can check out this fiddle