ovi.ro

ovi.ro

jQuery Custom Autocomplete with two columns

How to create 2 columns autocomplete.

This is a little bit non w3c compilant, but it works fine:)

<style>
.resultBox{ float: left; width: 50%!important;}
</style>
<input type="text" id="search-box">

The ideea is to add two divs inside the results ul and render each result in the proper div

$.widget( "custom.twocolumnsautocomplete", $.ui.autocomplete, {
		_renderMenu: function( ul, items ) {
			var that = this,
			currentCategory = "";
			ul.addClass('searchAutocomplete');
			// insert columns for the 2 categories: artists and songs
			ul.append('<div class="cat1 resultBox"><li>Category1</li></div>');
			ul.append('<div class="cat2 resultBox"><li>Category2</li></div>');
			$.each( items, function( index, item ) {
				// render li items for each category
				that._renderItem( ul.find('.'+ item.category ), item );
			});
		}
	});

var data = [
  {label: 'AAA', value: 'aaa', category: 'cat1'},
  {label: 'ABB', value: 'abb', category: 'cat2'}
];

$('#search-box').twocolumnsautocomplete({
  source: data
});

Demo http://jsfiddle.net/ovi_mihai/Ybjq4/7/

For ajax data, please make sure the category ends up in your autocomplete return.

[EDIT] It seems there is a problem with the selection of items this doesn’t work as expected, it only looks good.