Question

I want to implement a search with typeahead functionality on my site and followed the instructions here: http://twitter.github.io/typeahead.js/examples/#custom-templates

However, the examples all show the typeahead as text so onclick just fills in the textbox.

What's a best way for me to modify this so that onclick the suggestions actually links to a page for the suggestion? E.g. typeahead returns 3 objects:

  • object 1: link 1
  • object 2: link 2
  • object 3: link 3

What should I do to have object 1..3 returned, and clicking on them takes user to link 1..3?

Was it helpful?

Solution

Write an simple example in http://jsfiddle.net/2RNFj/3/

You just need to provide the objects and supply it to Bloodhound to set the source of typehead:

var links = [{name: "abc", link: "http://www.example1.com"}, 
             {name: "nbc", link: "http://www.example2.com"}];

var source = new Bloodhound({
  datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name'),
  queryTokenizer: Bloodhound.tokenizers.whitespace,
  local: links
});

source.initialize();

$('#custom-templates .typeahead').typeahead(null, {
  name: 'matched-links',
  displayKey: 'name',
  source: source.ttAdapter(),
  templates: {
    empty: [
      '<div class="empty-message">',
      'unable to find any Best Picture winners that match the current query',
      '</div>'
    ].join('\n'),
      suggestion: Handlebars.compile('<p><a href="{{link}}">{{name}}</a></p>')
  }
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top