I’m having a h… of a time figuring out why my jQuery autocomplete with categories and formatted results is not working. I’ve gone through a bunch of the similar questions on SO and tried every suggestion that I could find, but nothing seems to be working.
While the display is correct, it is not appending the list items to the top ul. It adds one, and then each subsequent result is appended to the same list item. This means that focus and selection methods do not work as intended.
I’ve tried:
_renderItemData(ul, item)vs._renderItem(ul, item)- With and without the
.data("item.autocomplete", item)inrenderItem() - Appending
.data("item.autocomplete", {})to theul.appendin the
renderMenu method - Changing the class used in the category list item.
Any help would be appreciated. Thanks!
Here’s the full code and the fiddle:
$(function () {
function format(item) {
var cell = '';
$.each(item.value, function(index, value) {
cell += "<a class='ui-autocomplete-thumbnail-link' href='" + value.url + "'>";
cell += "<img class='ui-autocomplete-thumbnail-image' src='" + value.images.small + "' />";
cell += value.presentation + "</a>";
});
return cell;
}
$.widget( "custom.categorycomplete", $.ui.autocomplete, {
_renderMenu: function(ul, items) {
var self = this, current_category = '';
$.each(items, function(index, item) {
if (item.label !== current_category) {
current_category = item.label;
ul.append($("<li class='ui-category'>" + current_category + "</li>").data("item.autocomplete", {}));
}
self._renderItem(ul, item);
});
}
});
var jsondata = [
{
"value": [
{
"id": 1,
"name": "category1-name1",
"presentation": "category1-presentation1",
"url": "example.com/category1-url1",
"images": {
"small": "http://sipi.usc.edu/database/preview/misc/4.1.07.png"
}
},
{
"id": 2,
"name": "category1-name2",
"presentation": "category1-presentation2",
"url": "example.com/category1-url2",
"images": {
"small": "http://sipi.usc.edu/database/preview/misc/4.1.08.png"
}
}
],
"label": "category1"
},
{
"value": [
{
"id": 3,
"name": "category2-name1",
"presentation": "category2-presentation1",
"url": "example.com/category2-url1",
"images": {
"small": "http://sipi.usc.edu/database/preview/misc/4.1.01.png"
}
},
{
"id": 4,
"name": "category2-name2",
"presentation": "category2-presentation2",
"url": "example.com/category2-url2",
"images": {
"small": "http://sipi.usc.edu/database/preview/misc/4.1.03.png"
}
}
],
"label": "category2"
}
];
$('#s1').categorycomplete({
source: jsondata,
select: function (event, ui) {
window.location.href = ui.item.value[0].url.replace(window.location.host, '');
return false;
}
})
.data( "categorycomplete" )._renderItem = function( ul, item ) {
return $( "<li>" )
.data("item.autocomplete", item)
.append(format(item))
.appendTo(ul);
};
});
You probably want something like this, note restructured JSON:
DEMO: http://jsfiddle.net/xQEsK/