jQuery Multi-column Autocomplete
Demo of a multi-column autocomplete textbox using jQuery.
by MrSnrub
HTML
<script src="https://code.jquery.com/ui/1.11.2/jquery-ui.min.js"></script>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.css">
<div id="div-container" style="margin:10px 10px;padding:8px;width:400px;"
class="ui-widget ui-widget-content ui-corner-all">
<div style="margin:0 0 4px 4px;">Enter a color:</div>
<input id="search" type="text" style="padding:2px;font-size:.8em;width:300px;" />
<div style="margin:20px 0 0 0;">
<span id="results" style="color:#68a;"></span>
</div>
</div>
CSS
body {
line-height: 1.25;
font-size: 13px;
}
ul.ui-widget {
font-size: 13px;
border: 0;
}
ul.ui-widget li.ui-menu-item {
list-style-image: none;
font-family: "Helvetica Neue",HelveticaNeue,helvetica,arial,sans-serif;
font-size: 92%;
font-weight: 300;
font-style: normal;
font-size-adjust: none;
margin: 0;
padding: 1.8px 4.55px;
white-space: nowrap;
}
.ui-widget-content a {
color: #444444;
}
ul.ui-widget li.ui-menu-item b {
font-weight: 700;
}
#search {
height: 25px;
}
.ui-widget-content .ui-state-focus
{
background-color: #D6F7FF;
background-image: none;
border: 0;
}
JavaScript
/*
* jQuery UI Multicolumn Autocomplete Widget Plugin 2.1
* Copyright (c) 2012-2014 Mark Harmon
*
* Depends:
* - jQuery UI Autocomplete widget
*
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*/
$.widget('custom.mcautocomplete', $.ui.autocomplete, {
_create: function () {
this._super();
this.widget().menu("option", "items", "> :not(.ui-widget-header)");
},
_renderMenu: function (ul, items) {
var self = this,
thead;
if (this.options.showHeader) {
table = $('<div class="ui-widget-header" style="width:100%"></div>');
$.each(this.options.columns, function (index, item) {
table.append('<span style="padding:0 4px;float:left;width:' + item.width + ';">' + item.name + '</span>');
});
table.append('<div style="clear: both;"></div>');
ul.append(table);
}
$.each(items, function (index, item) {
self._renderItem(ul, item);
});
},
_renderItem: function (ul, item) {
var t = '',
result = '';
$.each(this.options.columns, function (index, column) {
var whole_word = item[column.valueField ? column.valueField : index];
var current_search_string = document.getElementById("search").value;
// Highlight current search term.
var regex = new RegExp( '(' +
current_search_string + ')', 'gi' );
whole_word = whole_word.replace(
regex, "<b>$1</b>" );
t += '<span style="padding:0 4px;float:left;width:' + column.width + ';">' + whole_word + '</span>';
});
result = $('<li></li>')
.data('ui-autocomplete-item', item)
.append('<a class="mcacAnchor">' + t + '<div style="clear: both;"></div></a>')
.appendTo(ul);
return result;
...