Skip to content

Instantly share code, notes, and snippets.

@rendom
Created September 8, 2014 15:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rendom/1d85fe3ecb1476832ea7 to your computer and use it in GitHub Desktop.
Save rendom/1d85fe3ecb1476832ea7 to your computer and use it in GitHub Desktop.
Bootstrap 3 Typeahead, using objects.
function getData(callback){
// Cache & Ajax logix
callback([{id:1, name:'foo', text: 'huhu'}, {id:1, name:'baar', text: 'Lorem ipsum dolor sit amet.'}]);
}
$seleceted = $(".selected");
$('.input').typeahead({
minLength: 0,
render: function (items) {
console.log(items);
// Ignore selected values
var that = this;
var selected = [];
for (var i = $seleceted.length - 1; i >= 0; i--) {
selected.push( $(selected[i]).val() );
};
items = $(items).map(function (i, item) {
if(selected.indexOf(item.id) != -1) return;
i = $(that.options.item).data('value', item);
i.find('a').html(that.highlighter(item.name)+' ('+item.text+')');
return i[0];
});
if (this.autoSelect) {
items.first().addClass('active');
}
this.$menu.html(items);
return this;
},
source: function (query, process) {
getData(process);
},
updater: function(item){
this.$element.siblings('.selected').val(item.id);
return item.name + ' ('+ item.text+')';
},
matcher: function (item) {
if (item.name.toLowerCase().indexOf(this.query.trim().toLowerCase()) != -1) {
return true;
}
},
sorter: function (items) {
return items.sort(function(a,b){
return a.name > b.name;
});
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment