Twitter Typeahead Search Suggest

This is now the replacement for Bootstrap 2’s typeahead as it is no longer in the docs for Bootstrap 3.

https://github.com/twitter/typeahead.js/

I admit this is better cleaner version but my god the docs are not good! So confusing and took me a while to work it out. Classic case of geeks expecting you to know what they know. Here are some helpful tips.

First things first, I don’t know why they never show an example of ‘on selected do this’ event. That’s the main reason for typehead, you want to redirect to a page mostly upon selecting the suggestion… Anyway after lots of searching found an example. Yay..

https://github.com/twitter/typeahead.js/issues/300

Secondly I always use remote dataset but struggled to find an example dataset. In a nut shell this can be a json object like so where value is the default field typehead uses to search with.

[code]
//jquery
$(‘#user-search’).typeahead({
name: ‘ad_users’,
valueKey: ‘name’, //this is the field in your data set that typehead searches, if not defined default is ‘value’
limit: 10,
remote: ‘MY_URL/ajax/searchuser/q/%QUERY’ //%QUERY is automatically replaced with whatever you type in the search field
});

//bind on selected do this
//datum is the json object and username is my field I want to return, in my case I also wanted to return the result in lowercase
$(‘#user-search’).bind(‘typeahead:selected’, function(obj, datum, name) {
document.location = ‘MY_URL/staff/adcompare/ad-id/’+ datum.username.toLowerCase();
});
[/code]

Here is an example of my remote data set.

[code]
[
{"name":"Cabrinha (Pryde Group)","username":"Cabrinha"},
{"name":"Class Clendar","username":"Classcalendar"},
{"name":"Carafino","username":"Carafino"},{"name":"Calibro9","username":"Calibro9"}
]
[/code]

Seems so simple but took me ages to get this right as serious lack of examples in the docs 🙁