0

I have setup an autocomplete searchbar with jquery. When I type a part of a searchterm the suggestions pop-up, when I click the suggestion I get redirected to a new page (of the suggestion) which is good.

When I type a part of a searchterm and press ENTER the first searchterm gets displayed in the searchbar.

But when I press Enter I want to get redirected to a new page (of the first suggestion).

How can I go about this?

My HTML:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.16/themes/black-tie/jquery-ui.css">
<script type="text/javascript" src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>


<div class="searchbar">
    <input class="field_values"  id="autocomplete" placeholder="Search..."/>
    <button type="submit" id="searchbutton" class="icon" onclick = ""><i class="fa fa-search"></i></button>
</div>

My Javacript:

$(function() {
  var projects = [{
    label: "Bitcoin (BTC)",
    icon: "./alt/alt_logo/bitcoin.png",
    href: "./alt/alt_info/bitcoin.html"
  }, {
    label: "Ethereum (ETH)",
    icon: "./alt/alt_logo/ethereum.png",
    href: "./alt/alt_logo/bitcoin.png"
  }];

  $(".field_values").autocomplete({
    autoFocus: true,
    source: projects,
    create: function() {
      $(this).data('ui-autocomplete')._renderItem = function(ul, item) {
        return $('<li>')
          .append('<a href="' + item.href + '"><img class="icon" src="' + item.icon + '" />'  + item.label + '</span>' + '<br>'  + '</a>')
          .appendTo(ul);
      };
    }  
  });
});

Thanks for reading I hope someone can help me!

PS:- dont mind the dummy href's in the javascript

Reginald1234
  • 195
  • 8
  • Possible duplicate of [jQuery preventing postback on button click](https://stackoverflow.com/questions/887923/jquery-preventing-postback-on-button-click) – Heretic Monkey Mar 13 '18 at 20:38

1 Answers1

0
<button type="submit" id="searchbutton" class="icon" onKeydown=”Javascript: if (event.keyCode==13) create();><i class="fa fa-search"></i></button>

call create() onKeydown event with checking if keycode = 13