typeahead.js as a search function: multiple datasets

typeahead.js is a js library from Twitterland for building “robust typeaheads”.

What I found a bit confusing is how to get typeahead to act as a search function, so that once we’ve selected our chosen search term from the list of auto-completes, we are taken to a certain URL.

Let’s say we’ve set up typeahead (with the suggestion engine Bloodhound) for two datasets: poets and philosophers..

<div id="multiple-datasets">
<input class="typeahead" type="text" placeholder="Poets and Philosophers">
</div>
view raw gistfile1.html hosted with ❤ by GitHub
// In our DOM ready
var poets = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
limit:10,
prefetch: {
// url points to a json file that contains an array of poet names
// e.g. ['Baudelaire', 'Beckett']
url: './poets.json',
filter: function(list){
return $.map(list, function(poet) { return { name: poet }; });
}
}
});
var philosophers = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
limit:10,
prefetch: {
// url points to a json file that contains an array of philosopher names
// e.g. ['Descartes', 'Derrida']
url: './philosophers.json',
filter: function(list){
return $.map(list, function(philosopher) { return { name: philosopher }; });
}
}
});
poets.initialize();
philosophers.initialize();
$('#multiple-datasets .typeahead').typeahead({
highlight: true
},
{
name: 'poets',
displayKey: 'name',
source: poets.ttAdapter(),
templates: {
header: '<h3 class="league-name">Poets</h3>'
}
},
{
name: 'philosophers',
displayKey: 'name',
source: philosophers.ttAdapter(),
templates: {
header: '<h3 class="league-name">Philosophers</h3>'
}
});
view raw gistfile1.js hosted with ❤ by GitHub

When we types ‘De’ into the input field, both ‘Descartes’ and ‘Derrida’ will auto-complete. Now, we want to go to ‘[root]/philosophers/descartes’ when we select ‘Descartes’ from this auto-completed list. To do this, we must add

$('#multiple-datasets .typeahead').on('typeahead:selected',function(event, item, name){
// item is { name: 'Descartes' }
// name is 'philosophers'
var path = name+'/'+item.name;
url = 'http://localhost:3000/&#39;+path;
window.location = url;
});
view raw gistfile1.js hosted with ❤ by GitHub

after our existing typeahead code.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s