How to detect pressing Enter on keyboard using jQuery?

后端 未结 18 2228
有刺的猬
有刺的猬 2020-11-22 11:07

I would like to detect whether the user has pressed Enter using jQuery.

How is this possible? Does it require a plugin?

EDIT: It looks like I need

相关标签:
18条回答
  • 2020-11-22 11:23

    As the keypress event isn't covered by any official specification, the actual behavior encountered when using it may differ across browsers, browser versions, and platforms.

    $(document).keydown(function(event) {
      if (event.keyCode || event.which === 13) {
        // Cancel the default action, if needed
        event.preventDefault();
        //call function, trigger events and everything tou want to dd . ex : Trigger the button element with a click
        $("#btn").trigger('click');
      }
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <button id="btn" onclick="console.log('Button Pressed.')">&nbsp</button>

    I hope it would be useful!

    0 讨论(0)
  • 2020-11-22 11:25

    The whole point of jQuery is that you don't have to worry about browser differences. I am pretty sure you can safely go with enter being 13 in all browsers. So with that in mind, you can do this:

    $(document).on('keypress',function(e) {
        if(e.which == 13) {
            alert('You pressed enter!');
        }
    });
    
    0 讨论(0)
  • 2020-11-22 11:26

    I think the simplest method would be using vanilla javacript:

    document.onkeyup = function(event) {
       if (event.key === 13){
         alert("enter was pressed");
       }
    }
    
    0 讨论(0)
  • 2020-11-22 11:26
    $(function(){
      $('.modal-content').keypress(function(e){
        debugger
         var id = this.children[2].children[0].id;
           if(e.which == 13) {
             e.preventDefault();
             $("#"+id).click();
           }
       })
    });
    
    0 讨论(0)
  • 2020-11-22 11:27

    I couldn't get the code posted by @Paolo Bergantino to work but when I changed it to $(document) and e.which instead of e.keyCode then I found it to work faultlessly.

    $(document).keypress(function(e) {
        if(e.which == 13) {
            alert('You pressed enter!');
        }
    });
    

    Link to example on JS Bin

    0 讨论(0)
  • 2020-11-22 11:28

    I spent sometime coming up with this solution i hope it helps someone.

    $(document).ready(function(){
    
      $('#loginforms').keypress(function(e) {
        if (e.which == 13) {
        //e.preventDefault();
        alert('login pressed');
        }
      });
    
     $('#signupforms').keypress(function(e) {
        if (e.which == 13) {
          //e.preventDefault();
          alert('register');
        }
      });
    
    });
    
    0 讨论(0)
提交回复
热议问题