I'm trying to implement a search box with typeahead.js where the user can navigate to entries by clicking on line items in typeahead or using keyboard up and down to select entry and navigate to them by enter key.

This is my html

<div id="remote">
  <input class="typeahead" type="text" placeholder="Search for people"> 
</div>

This is my javascript

$(document).ready(function() {
var castDirectors = new Bloodhound({
  datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
  queryTokenizer: Bloodhound.tokenizers.whitespace,
  prefetch: '../api/v1/search/people_typeahead',
  remote: '../api/v1/search/people_typeahead?q=%QUERY',
    dupDetector: function(remoteMatch, localMatch) {
        return remoteMatch.value === localMatch.value;
    }
});

castDirectors.initialize();

$('#remote .typeahead').typeahead(null, {
  name: 'cast-directors',
  displayKey: 'value',
  source: castDirectors.ttAdapter(),
    templates: {
        empty: [
      '<div class="empty-message">',
      'no matching names',
      '</div>'
    ].join('\n'),
        suggestion: Handlebars.compile('<p><a id="typeahead" href="{{link}}">{{value}}</a></p>')
    }       
});
});

With the input type="text", if I navigate with keyboard and select with enter key, it just fills the textbox. I'd like the enter key to equate to clicking on the line item. What do I need to change?

有帮助吗?

解决方案

Managed to add the following to my javascript and it worked nicely

$('#remote .typeahead').on('typeahead:selected', function (e, datum) {
    window.location.href = datum.link
});

其他提示

Don't put a href inside your items. But inside your typeahead use select function like below:

 select: function( event, key ) {
            window.location.href ="Your-Key-related-url-here";
        }

Its working for me. Let me know for any further issue.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top