jQuery UI Autocomplete Category Grouping
An attempt to convert the category example into horizontal groups
by Brian Bond
HTML
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css">
<label for="search">Search: </label>
<input id="search">
CSS
.ui-autocomplete-category {
font-weight: bold;
padding: .2em .4em;
margin: .8em 0 .2em;
line-height: 1.5;
}
.ui-menu .ui-menu-item {
width: 220px;
display: inline-block;
clear: both;
}
.Products {
float: left;
width: 220px;
}
.People {
float: right;
width: 220px;
}
JavaScript
$.widget( "custom.catcomplete", $.ui.autocomplete, {
_create: function() {
this._super();
this.widget().menu( "option", "items", "> :not(.ui-autocomplete-category)" );
},
_resizeMenu: function() {
this.menu.element.outerWidth(470).outerHeight(300);
},
_renderMenu: function( ul, items ) {
var that = this,
currentCategory = "";
$.each( items, function( index, item ) {
var li;
if ( item.category != currentCategory ) {
ul.append( "<li class='ui-autocomplete-category " + item.category + "'>" + item.category + "</li>" );
currentCategory = item.category;
}
li = that._renderItemData( ul, item );
if ( item.category ) {
li.attr( "aria-label", item.category + " : " + item.label );
}
});
},
_renderItem: function( ul, item ) {
return $( "<li>" )
.addClass(item.category)
.attr( "data-value", item.value )
.append( $( "<a>" ).text( item.label ) )
.appendTo( ul );
}
});
$(function() {
var data = [
{ label: "annhhx10", category: "Products" },
{ label: "annk K12", category: "Products" },
{ label: "annttop C13", category: "Products" },
{ label: "anders andersson", category: "People" },
{ label: "andreas andersson", category: "People" },
{ label: "andreas johnson", category: "People" }
];
$( "#search" ).catcomplete({
delay: 0,
source: data
});
});