Skip to content

Disable form submit on enter | Example using JavaScript

  • by

Check to see what key you have pressed if it is an enter key then use preventDefault() method in the event, which will stop the form from submitting.

The “keyCode” property returns the Unicode character code of the key that triggered the keypress event.

JavaScript example disable form submit on entering

HTML example code.

If you are filling out an input field and press the enter key it will submit the form, even if you haven’t finished filling in the rest of the information.

The following code will show you how you can turn off the enter key using

el.addEventListener("keypress", function(event) {
      if (event.key === "Enter") { // or can use even.keycode == 13

        event.preventDefault();
      }
    });

Complete code

<!DOCTYPE html>
<html>
<body>
  <form id="my-form">
    <input type="text" id="myInputID">
    <button type="submit" onclick="submit()">Submit</button>
  </form>

  <script>
    var el = document.getElementById("myInputID");
    el.addEventListener("keypress", function(event) {
      if (event.key === "Enter") {
        alert(event.key  + " " + event.which);
        event.preventDefault();
      }
    });

  </script>
</body>
</html>

Output:

Disable form submit on enter

Do comment if you have any doubts or suggestions on this JS form topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *