Run Jquery method when enter key is pressed

后端 未结 4 642
自闭症患者
自闭症患者 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()

    0 讨论(0)
  • 2021-01-14 02:32

    var ENTER_KEY = 13;
    var user_key;
    $(document).on('keydown', function(e){
      user_key = e.keyCode || e.which
       if(user_key === ENTER_KEY) { 
          document.querySelector("#button").click();
       }
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <button id="button" onclick="console.log('button pressed')">button</button>

    0 讨论(0)
  • 2021-01-14 02:39
    $(".input_loginform").keypress(function(e){
        if (e.which == 13){
            e.preventDefault();
            alert("User pressed 'Enter' in a text input. sender form #"+this.form.id);
            postlogin("#"+this.form.id);
        }
    });
    
    0 讨论(0)
  • 2021-01-14 02:46
    $(document).keydown(function(e) {
       // test for the enter key
       if (e.keyCode == 13) {
          // Do your function
          myFunction();
       }
    });
    
    0 讨论(0)
提交回复
热议问题