Trigger a button click with JavaScript on the Enter key in a text box

后端 未结 30 1918
难免孤独
难免孤独 2020-11-21 23:53

I have one text input and one button (see below). How can I use JavaScript to trigger the button\'s click event when the Enter key is pressed ins

30条回答
  •  迷失自我
    2020-11-22 00:36

    In plain JavaScript,

    if (document.layers) {
      document.captureEvents(Event.KEYDOWN);
    }
    
    document.onkeydown = function (evt) {
      var keyCode = evt ? (evt.which ? evt.which : evt.keyCode) : event.keyCode;
      if (keyCode == 13) {
        // For Enter.
        // Your function here.
      }
      if (keyCode == 27) {
        // For Escape.
        // Your function here.
      } else {
        return true;
      }
    };
    

    I noticed that the reply is given in jQuery only, so I thought of giving something in plain JavaScript as well.

提交回复
热议问题