Skip to content

Instantly share code, notes, and snippets.

@developerdizzle
Last active August 29, 2015 14:05
Show Gist options
  • Save developerdizzle/33b918e619f2f06fe19b to your computer and use it in GitHub Desktop.
Save developerdizzle/33b918e619f2f06fe19b to your computer and use it in GitHub Desktop.
Bootstrap Typeahead repeated/multiple suggestions
/*
While trying to figure out how to get typeahead to allow multiple suggestions/matches per textbox,
I found bassjobsen's awesome Bootstrap-3-Typeahead repo - https://github.com/bassjobsen/Bootstrap-3-Typeahead.
I was able to use that to accomplish what I wanted. I wasn't able to get it working with the latest typeahead.js.
It will let you continue typing after the first suggestion, and append future suggestions into the textbox.
*/
var source = ['Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California',
'Colorado', 'Connecticut', 'Delaware', 'Florida', 'Georgia', 'Hawaii',
'Idaho', 'Illinois', 'Indiana', 'Iowa', 'Kansas', 'Kentucky', 'Louisiana',
'Maine', 'Maryland', 'Massachusetts', 'Michigan', 'Minnesota',
'Mississippi', 'Missouri', 'Montana', 'Nebraska', 'Nevada', 'New Hampshire',
'New Jersey', 'New Mexico', 'New York', 'North Carolina', 'North Dakota',
'Ohio', 'Oklahoma', 'Oregon', 'Pennsylvania', 'Rhode Island',
'South Carolina', 'South Dakota', 'Tennessee', 'Texas', 'Utah', 'Vermont',
'Virginia', 'Washington', 'West Virginia', 'Wisconsin', 'Wyoming'
];
$('.typeahead').typeahead({
source: source,
matcher: function(item) {
var q = _.last(this.query.split(' ')).trim();
if (q) {
//startsWith - you can do whatever logic you want, including Bloodhound
return item.indexOf(q) == 0;
}
return false;
},
updater: function(item) {
var q = this.query.split(' ');
q[q.length-1] = item;
return q.join(' ');
},
highlighter: function (item) {
var q = this.query.split(' ');
var last = q[q.length-1].trim();
var query = last.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, '\\$&');
return item.replace(new RegExp('(' + query + ')', 'ig'), function ($1, match) {
return '<strong>' + match + '</strong>';
});
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment