Practical Web Programming

Thursday, June 20, 2013

Trigger Button Click on Enter Key in TextInput

Most of the time when you are in a search form, google search for example, after typing in your search phrase, you want to trigger the search by just pressing the Enter key in your keyboard. How annoying it would be if your have to reach for the mouse hit the search button with your cursor? Luckily, this is easily implemented in jQuery. 

Here's the full code example:
<html>
  <head>
    <title>Search on Enter key</title>
    <script type="text/javascript">
      $(document).ready(function() {
        $("#search_text").on('keyup', function(event){
          if(event.keyCode == 13) {
            $("#search_button").click();
          }
        });
        $("#search_button").on('click', function(e) {
          alert("You clicked me!");
        });
      });
    </script>
  </head>
  <body>
    <div>
      <input id="search_text" type="text" value=""/>
      <button id="search_button" href="#">Search</button>
    </div>
  </body>
</html>

0 comments:

Recent Post