How to press enter key go to search page Twitter typeahead?

Some days ago when i was working with the Twitter typeahead auto-complete from on my laravel application, But when i was press the enter key, it’s not redirect to my result page. But I want to redirect on my result page on that way i can easily display all the records of matching search text.

I did try to solve this many way finally i solve this simply. I was found way by using jquery “on keypress” event. So we can see this in the bellow code how it is work. So let’s see the bellow example:

Now in this example when we press the enter on search input box. Then it will redirect on the search page as like as 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>

Read Also: How to implement infinite ajax scroll pagination in Laravel?

Thanks for read. I hope it help you. For more you can follow us on facebook

Shahriar Sagor

My name is Shahriar sagor. I'm a developer. I live in Bangladesh and I love to write tutorials and tips that will help to other Developer's. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.