0

I have a link that function as the submit button of the search bar:

<a href="#" id="search"><img src="images/go.png" /></a>

Is there anyway I can set enter as the hotkey for that link?

For example, when user press enter it will automatically fire the link and start searching, just like google.

This is what I got so far, but seems like it doesn't work:

    addEventListener("keypress", function (event) {
        if (event.keyCode == 13)
            $('search').trigger('click');
    });
Amit Verma
  • 40,709
  • 21
  • 93
  • 115
SSilicon
  • 253
  • 1
  • 2
  • 16
  • This link might be what you're looking for. http://stackoverflow.com/questions/905222/enter-key-press-event-in-javascript – dsiebert424 Aug 07 '14 at 20:22
  • 1
    Funny that you should mention google. Pressing a key sounds like an event. Javascript handles events. Start there. If you get stuck, post what you have tried, and then I am sure you will find lots of help here. – Nick Zimmerman Aug 07 '14 at 20:22

2 Answers2

1

Wrappe your search bar component in a form tag. It will automatically set the enter key as the default hotkey to fire a search event.

Exemple:

<form action="someServerSideFileToHandleTheSearchInput">
    <input type="text"><!-- I think you have a input form here? -->
    <a href="#" id="search"><img src="images/go.png" /></a>
</form>

That's good because it will keep working even if people disable javascript in their browsers.

0

stealing this snip from here, full credit to @TheSuperTramp for his original answer

if you are only trying to submit the form when enter is pressed in the search box and not the entire document then this should get you in the right direction

$('#textarea').bind("enterKey",function(e){
    //submit your search here
});
$('#textarea').keyup(function(e){
    if(e.keyCode == 13)
    {
      $(this).trigger("enterKey");
    }
});
Community
  • 1
  • 1
workabyte
  • 3,496
  • 2
  • 27
  • 35