jQuery - Target button with enter key when input field is focused

后端 未结 5 1945
无人共我
无人共我 2021-02-01 04:33

I have an input field and a login button. I want to allow users to hit the \"enter\" key to click the button when the input field is focused. How would I do this with jQuery?<

5条回答
  •  臣服心动
    2021-02-01 05:19

    If they're in the same form and you change the button to be type="submit" you should find it happens automatically, but anyway...

    $(document).ready(function() {
    
       $('#loginUserID').keypress(function(e){
          if(e.which === 13)
             $('#loginBtn').click();
       });
    
    });
    

    (Or you may prefer .keyup or .keydown.)

提交回复
热议问题