Twitter Typeahead Press Enter Key Go to Search Page

By Hardik Savani June 15, 2023 Category : Javascript Bootstrap jQuery

When i was working with Twitter typeahead auto-complete on my laravel 5 application, But when i press enter key, it's not redirect on my result page. I want to redirect on my result page that way i can display all records of matching search text.

I did try to solve many way but i can't solve simply. At last i found way using jquery "on keypress" event. You can see bellow code how it is work. So let's see bellow example:

In this example when you press enter on search input box. it will redirect on search page like bellow path:

http://test.hd/search?q=Ala

Example:

<!DOCTYPE html>

<html>

<head>

<title>Twitter typeahead press enter key go to search page</title>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/corejs-typeahead/0.11.1/typeahead.jquery.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/corejs-typeahead/0.11.1/typeahead.bundle.min.js"></script>

</head>

<body>


<input type="text" class="typeahead" />


<script type="text/javascript">


var states = ['Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California','Colorado', 'Connecticut', 'Delaware', 'Florida', 'Georgia', 'Hawaii'];


var states = new Bloodhound({

datumTokenizer: Bloodhound.tokenizers.whitespace,

queryTokenizer: Bloodhound.tokenizers.whitespace,

local: states

});


$('.typeahead').typeahead({

hint: true,

highlight: true,

minLength: 1

},

{

name: 'states',

source: states

}).on('keypress', function(e) {

if (e.which == 13) {

var q = $('input.typeahead.tt-input').val();

window.location.href = "/search?q="+q;

}

});

</script>


</body>

</html>

Shares