How to detect pressing Enter on keyboard using jQuery?

后端 未结 18 2391
有刺的猬
有刺的猬 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:37

    The easy way to detect whether the user has pressed enter is to use key number the enter key number is =13 to check the value of key in your device

    $("input").keypress(function (e) {
      if (e.which == 32 || (65 <= e.which && e.which <= 65 + 25)
                        || (97 <= e.which && e.which <= 97 + 25)) {
        var c = String.fromCharCode(e.which);
        $("p").append($(""))
              .children(":last")
              .append(document.createTextNode(c));
      } else if (e.which == 8) {
        // backspace in IE only be on keydown
        $("p").children(":last").remove();
      }
      $("div").text(e.which);
    });
    

    by pressing the enter key you will get result as 13 . using the key value you can call a function or do whatever you wish

            $(document).keypress(function(e) {
          if(e.which == 13) {
    console.log("User entered Enter key");
              // the code you want to run 
          }
        });
    

    if you want to target a button once enter key is pressed you can use the code

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

    Hope it help

提交回复
热议问题