I was trying to use the bootstrap typeahead for a simple project and it took me more than 3 hours... you see, the web is full of examples, but most posters I found only give you half the answer: how to show it.
Like that's all one needs to do... we live in the real world, so we need to show it and then do something when the user selects an option.
For that, most give the example below, which is made of parts copy-pasted from different places, I guess.
I could not get this to work... first of all, all examples wrongly use $('.typeahead')
while the class of the input is not typeahead
so that's not going to work (even the main Bootstrap example). Then the callback for that event - it just does not work for me, period!
<input autocomplete="off" type="text" class="col-sm-2" data-provide="typeahead" >
$('.typeahead').typeahead({
source: items,
}).on('typeahead:selected', function(evt, item) {
console.log(item);
})
The way I got it to work, after a lot of pray-programming and googling:
<input autocomplete="off" type="text" class="typeahead search-query col-sm-2" data-provide="typeahead">
<script src="bootstrap/js/bootstrap-typeahead.js"></script>
<script>
var items = ['1','2'];
$('.typeahead').typeahead({
source: items,
updater: function (item) {
window.location.href = item;
}
})
</script>
Make sure to include the script tags towards the end of the document, so you allow the browser a chance to render the page faster.
Note that the class of the input is set to typeahead
, the .js script is included. The search-query
class makes it look like a nice search box, from Bootstrap.
I still use Bootstrap 2.3.2 and, by the way, the bootstrap-typeahead.js script for this is found if you go to the bootstrap site for 2.3.2, go to the page with the typeahead example and see the .js scripts it loads...
I'm not a javascript guru or an html maven - just a guy that want's to make a nice page quickly...
Enjoy!