Typeahead.js enter key search

I am trying to implement a search box using typeahead.js where the user can go to the record by clicking on the positions in typeahead or using the keyboard up and down to select the record and go to it by pressing the 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 input type = "text", if I navigate the keyboard and select the enter key, it just fills the text box. I would like the input key to be equated to clicking on a position. What do i need to change?

+4
source share
2 answers

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

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

href . typeahead select, :

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

. - .

+1

Source: https://habr.com/ru/post/1539856/


All Articles