Handling the “Enter” / “Return” key in Chrome

前端 未结 3 841
猫巷女王i
猫巷女王i 2021-01-19 02:52

I have an AJAX-y type page. When the user clicks \"GO\" I need to execute a specific javascript function. I also want to simulate the \"GO\" click when a user hits \"Enter\"

相关标签:
3条回答
  • 2021-01-19 03:10

    I agree with BGerrissen, that is the best approach. However, to better adapt to your code you can just add the stops to your current function:

    $(document).ready(function () {  
      $('#root').keypress(function(e) { 
        if (e.keyCode == '13') { 
          e.preventDefault();//Stops the default action for the key pressed
          goButton(); 
          return false;//extra caution, may not be necessary
        } 
      });
    });
    
    0 讨论(0)
  • 2021-01-19 03:15

    Try returning false directly after your if statement (which calls goButton()).

    See an example here: Using jQuery to prevent form submit when enter is pressed

    0 讨论(0)
  • 2021-01-19 03:25

    Assuming you have a form:

    $('#theForm').submit(function(e){
        e.preventDefault();
        goButton();
        return false; // just to be sure.
    });
    

    You need to prevent the submit event from the form, which gets called when the form has focus and a user presses enter.

    0 讨论(0)
提交回复
热议问题