Skip to content

Instantly share code, notes, and snippets.

@csrui
Created August 7, 2013 10:46
Show Gist options
  • Save csrui/6173015 to your computer and use it in GitHub Desktop.
Save csrui/6173015 to your computer and use it in GitHub Desktop.
Twitter Bootstrap customizations
/*
Extended Bootstrap Typeahead
Based on an answer on stackexchange.com
http://stackoverflow.com/a/14959406/1065537
*/
/* Enhances the autocomplete function */
$('.autocomplete').typeahead({
source: function (query, process) {
return $.ajax({
url: this.$element.data('link'),
type: 'get',
data: { q: query },
dataType: 'json',
success: function (result) {
var resultList = result.map(function (item) {
var aItem = { id: item.id, name: item.name };
return JSON.stringify(aItem);
});
return process(resultList);
}
});
},
matcher: function (obj) {
var item = JSON.parse(obj);
return ~item.name.toLowerCase().indexOf(this.query.toLowerCase());
},
sorter: function (items) {
var beginswith = [], caseSensitive = [], caseInsensitive = [], item;
while (aItem = items.shift()) {
var item = JSON.parse(aItem);
if (!item.name.toLowerCase().indexOf(this.query.toLowerCase())) beginswith.push(JSON.stringify(item));
else if (~item.name.indexOf(this.query)) caseSensitive.push(JSON.stringify(item));
else caseInsensitive.push(JSON.stringify(item));
}
return beginswith.concat(caseSensitive, caseInsensitive);
},
highlighter: function (obj) {
var item = JSON.parse(obj);
var query = this.query.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, '\\$&');
return item.name.replace(new RegExp('(' + query + ')', 'ig'), function ($1, match) {
return '<strong>' + match + '</strong>';
});
},
updater: function (obj) {
var item = JSON.parse(obj);
$('#' + this.$element.data('target')).attr('value', item.id);
return item.name;
}
});
/* Clears the target input */
$('.autocomplete').on('change', function() {
var target = $(this).data('target');
if ($(this).val().length === 0) {
$('#' + target).val('');
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment