Sunday, April 24, 2011

jqueryui autocomplete optgroup

autocomplete's combobox doesn't support by default the optgroups, so here is what I did,http://www.blogger.com/img/blank.gif
I search every options item in the select to see it it belongs thttp://www.blogger.com/img/blank.gifo a optgroup, then I set the 'category' variable as needed...

that is, I tweaked a little the base code in jqueryui's example, joining combobox and categories

update: the complete code is here: http://bin.cakephp.org/view/73871691

but an approximation can be read in what follows

modified default's "source" method:
source:
function( request, response ) {
var matcher = new RegExp( $.ui.autocomplete.escapeRegex(request.term), "i" );
response( select.find( "option" ).map(function() {
optgroup = $(select).find('option[value="'+this.value+'"]').parent('optgroup');
if (optgroup.length == 0) {
var item_category = 0;
} else {
var item_category = optgroup.attr('label');
}
var text = $( this ).text();
if ( this.value && ( !request.term || matcher.test(text) ) )
return {
label: text.replace(
label: text.replace(
new RegExp(
"(?![^&;]+;)(?!<[^<>]*)(" +
$.ui.autocomplete.escapeRegex(request.term) +
")(?![^<>]*>)(?![^&;]+;)", "gi"
), "<strong>$1</strong>"
)
value: text,
category: item_category,
option: this
};
}) );

then *override _renderMenu*, as the example in 'category' from jqeuryui, but with an extra tweak:
              input.data( "autocomplete" )._renderMenu = function( ul, items ) {
var self = this,
currentCategory = "";
$.each( items, function( index, item ) {
if (item.category == 0) {

} else if ( item.category != currentCategory ) {
ul.append( "<li class='ui-autocomplete-category'>" + item.category + "</li>" );
currentCategory = item.category;
}
self._renderItem( ul, item );
});
};