Enter key press event in JavaScript

2018-12-31 08:41发布

I have a form with two text boxes, one select drop down and one radio button. When the enter key is pressed, I want to call a javascript function (User defined), but when I press it, the form is submitted.

How do I prevent the form from being submitted when the enter key is pressed?

14条回答
何处买醉
2楼-- · 2018-12-31 09:11

Below code will add listener for ENTER key on entire page.

This can be very useful in screens with single Action button eg Login, Register, Submit etc.

<head>
        <!--Import jQuery IMPORTANT -->
        <script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>

         <!--Listen to Enter key event-->
        <script type="text/javascript">

            $(document).keypress(function (e) {
                if (e.which == 13 || event.keyCode == 13) {
                    alert('enter key is pressed');
                }
            });
        </script>
    </head>

Tested on all browsers.

查看更多
泛滥B
3楼-- · 2018-12-31 09:15

Use both event.which and event.keyCode:

function (event) {
    if (event.which == 13 || event.keyCode == 13) {
        //code to execute here
        return false;
    }
    return true;
};
查看更多
忆尘夕之涩
4楼-- · 2018-12-31 09:16

Override the onsubmit action of the form to be a call to your function and add return false after it, ie:

<form onsubmit="javascript:myfunc();return false;" >
查看更多
流年柔荑漫光年
5楼-- · 2018-12-31 09:18

A jQuery solution.

I came here looking for a way to delay the form submission until after the blur event on the text input had been fired.

$(selector).keyup(function(e){
  /*
   * Delay the enter key form submit till after the hidden
   * input is updated.
   */

  // No need to do anything if it's not the enter key
  // Also only e.which is needed as this is the jQuery event object.
  if (e.which !== 13) {
       return;
  }

  // Prevent form submit
  e.preventDefault();

  // Trigger the blur event.
  this.blur();

  // Submit the form.
  $(e.target).closest('form').submit();
});

Would be nice to get a more general version that fired all the delayed events rather than just the form submit.

查看更多
爱死公子算了
6楼-- · 2018-12-31 09:18

if you want to do it using purly java script here is an example that work perfectly

Let's say this is your html file

<!DOCTYPE html>
<html>
  <body style="width: 500px">
    <input type="text" id="textSearch"/> 
      <script type="text/javascript" src="public/js/popup.js"></script>
  </body>
</html>

in your popup.js file just use this function

var input = document.getElementById("textSearch");
input.addEventListener("keyup", function(event) {
    event.preventDefault();
    if (event.keyCode === 13) {
        alert("yes it works,I'm happy ");
    }
});
查看更多
孤独寂梦人
7楼-- · 2018-12-31 09:20
if(characterCode == 13)
{
    return false; // returning false will prevent the event from bubbling up.
}
else
{
    return true;
}

Ok, so imagine you have the following textbox in a form:

<input id="scriptBox" type="text" onkeypress="return runScript(event)" />

In order to run some "user defined" script from this text box when the enter key is pressed, and not have it submit the form, here is some sample code. Please note that this function doesn't do any error checking and most likely will only work in IE. To do this right you need a more robust solution, but you will get the general idea.

function runScript(e) {
    //See notes about 'which' and 'key'
    if (e.keyCode == 13) {
        var tb = document.getElementById("scriptBox");
        eval(tb.value);
        return false;
    }
}

returning the value of the function will alert the event handler not to bubble the event any further, and will prevent the keypress event from being handled further.

NOTE:

It's been pointed out that keyCode is now deprecated. The next best alternative which has also been deprecated.

Unfortunately the favored standard key, which is widely supported by modern browsers, has some dodgy behavior in IE and Edge. Anything older than IE11 would still need a polyfill.

Furthermore, while the deprecated warning is quite ominous about keyCode and which, removing those would represent a massive breaking change to untold numbers of legacy websites. For that reason, it is unlikely they are going anywhere anytime soon.

查看更多
登录 后发表回答