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 _renderItem
, 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 (_renderMenu
or _suggest
?)
$( "#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 );
};
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
ul.append("<table><thead><tr><th>ID#</th><th>Name</th><th>Cool Points</th></tr></thead><tbody></tbody></table>");
$.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 >"+item.id+"</td>"+"<td>"+item.value+"</td>"+"<td>"+item.cp+"</td>" )
.appendTo( table );
};
//random json values
var projects = [
{id:1,value:"Thomas",cp:134},
{id:65,value:"Richard",cp:1743},
{id:235,value:"Harold",cp:7342},
{id:78,value:"Santa Maria",cp:787},
{id:75,value:"Gunner",cp:788},
{id:124,value:"Shad",cp:124},
{id:1233,value:"Aziz",cp:3544},
{id:244,value:"Buet",cp:7847}
];
$( "#project" ).autocomplete({
minLength: 1,
source: projects,
//you can write for select too
focus: function( event, ui ) {
//console.log(ui.item.value);
$( "#project" ).val( ui.item.value );
$( "#project-id" ).val( ui.item.id );
$( "#project-description" ).html( ui.item.cp );
return false;
}
})
});
You can check out this fiddle