Run Jquery method when enter key is pressed

后端 未结 4 687
自闭症患者
自闭症患者 2021-01-14 02:09

I\'m trying to run a method when the enter key has been pressed. This method is already being used by a button. Basically, when the user fills in a text field and clicks a s

4条回答
  •  醉酒成梦
    2021-01-14 02:23

    You can bind a keypress event to the document and trigger() the handler on your button.

    $(document).bind('keypress', function(e){
       if(e.which === 13) { // return
          $('#buttonid').trigger('click');
       }
    });
    

    This would fire whenever you press the return key on your site. You probably want it only to happen if someone uses return in your input form. You would just need to change the selector from document to any kind of selector that matches your control.

    Ref.: .trigger()

提交回复
热议问题