jQuery UI Autocomplete categories with count mechanism
jQuery UI Autocomplete categories with count mechanism
HTML
<link rel="stylesheet" href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.17/themes/black-tie/jquery-ui.css">
<script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.17/jquery-ui.min.js"></script>
<div class="demo">
<label for="search">Search: </label>
<input id="search" />
</div>
CSS
.ui-autocomplete-category
{
font-weight: bold;
padding: .2em .4em;
margin: .8em 0 .2em;
line-height: 1.5;
}
JavaScript
a$.widget("custom.catcomplete", $.ui.autocomplete, {
_renderMenu: function (ul, items) {
var self = this,
currentCategory = "", itemCount = 0, itemsLength = items.length - 1;
$.each(items, function (index, item) {
if (item.category != currentCategory) {
ul.find('.ui-autocomplete-category:last').text(function () { return $(this).text() + ' ' + itemCount });
ul.append("<li class='ui-autocomplete-category'>" + item.category + "</li>");
currentCategory = item.category;
itemCount = 1;
}
else {
itemCount++;
}
if (index === itemsLength) {
ul.find('.ui-autocomplete-category:last').text(function () { return $(this).text() + ' ' + itemCount });
}
self._renderItem(ul, item);
});
}
});
$(function() {
var data = [
{ label: "anders", category: "" },
{ label: "andreas", category: "" },
{ label: "antal", category: "" },
{ 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
});
});