How to Stop Enter Key from Submitting the Form in Javascript

In this tutorial, you will learn how to stop enter key from submitting the form in javascript. The HTML form element is used to collect the data entered by the user and then sent to the server for further processing.

It is very common to have a submit button in the form to submit data to the server, but submission can also be triggered by simply pressing Enter key on the keyboard.

There are various ways to prevent form submission on Enter keypress. Generally, to prevent the default behavior of an element, we make use of the preventDefault() method. But in this tutorial, we will also use other properties and methods of the event object to accomplish our goal.

In the following example, we have a form element with a few child elements. We will prevent the submission of this form on Enter keypress. Please have a look over the code example and the steps given below.

HTML & CSS

  • We have multiple elements in the HTML file (div, form, button, input, label, and br).
  • The div element is just a wrapper for the rest of the elements. We are using style attribute with div element to center align the child elements.
  • We have a form element that has an id of “myForm”.
  • The innerText for the button element is “Submit”.
  • We have also included our javascript file script.js with a script tag at the bottom.
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>

    <div style="text-align: center;">
        <form action="/submission.php" id="myForm">
            <label for="fname">First name:</label>
            <input type="text" id="fname" name="fname">
            <br><br>
            <label for="lname">Last name:</label>
            <input type="text" id="lname" name="lname">
            <br><br>
            <button type="submit">Submit</button>
        </form>
    </div>

    <script src="script.js"></script>

</body>

</html>

Javascript

  • We have attached the keypress event to the document.
  • In the event handler function, we are calling the stopFormSubmission() method and passing the event object as a parameter. The returned Boolean value is stored in the result variable
  • If the result is true, we will call the preventDefault() method of the event object to prevent form submission.
  • In the stopFormSubmission() method, we have the hasForm variable set to false and we are using the if statement and key property of the event object to verify whether the user has pressed Enter key or not.
  • The compsedPath() method of the event object returns an array of EventTarget objects representing the objects on which an event listener will be invoked.
  • We are calling forEach() method on the array returned by the above step. In the anonymous function, we are using the getAttribute() method to get the id of the element and are storing it in the elementId variable.
  • We are using the if statement to verify whether the elementId matches the id of our form element or not. If yes, we will set hasForm to true.
  • Depending upon the value of hasForm, we are returning true or false.
document.addEventListener("keypress", (e) => {
  let result = stopFormSubmission(e);
  if (result) e.preventDefault();
});

function stopFormSubmission(e) {
  let hasForm = false;
  if (e.key == "Enter") {    
    e.composedPath().forEach((element) => {
      let elementId = element.getAttribute && element.getAttribute("id");
      if (elementId == "myForm") hasForm = true;
    });
  }

  if (hasForm) return true;
  else return false;
}