Search code examples
javascriptjqueryhtmlkeycode

.keydown() when press return key


I'm trying to get the option that when a user presses the Return key, the search button is triggered. Currently it can only be pressed on the search button, but sometimes users have the tendency to press the return key after the search entry.

$(document).ready(function() {
  $('#search-button').keydown(function(event){
    if (event.keyCode==13) {
       Trackster.searchTracksByTitle($("#search-input").val());
    }
  });
  $("#search-button").click(function(){
    Trackster.searchTracksByTitle($("#search-input").val());
  });
});

does anyone know what i did wrong here? i still cant use press return to trigger the search.


Solution

  • If you have a search input and a search button, an ideal practice is to get them wrapped by a form tag.

    <form id="search-form">
      <input type="text" id="search-input" ...>
      <button type="submit" id="search-button" ...>Search</button>
    </form>
    

    Notice that the type is set to submit. It makes the button act as a submit button for the form. Now you will have to listen to the submit event of the form. The return key binding comes for free. Plus, you don't have to listen to the keydown and click events separately.

    $(document).ready(function() {
      $('#search-form').submit(function(event) {
        event.preventDefault();
        Trackster.searchTracksByTitle($("#search-input").val());
      })
    });
    

    You will see that the search works when:

    1. User types something in textbox and hits the return key
    2. User types something in textbox and clicks on the submit button

    I believe this solves your issue.