Skip to content

Prevent form submission on Enter key press | Example Code

Use preventDefault() event method to Prevent form submission on the “Enter” key pressed in JavaScript. Enter key keycode is 13, so you can check in if statement.

Prevent form submission by hitting Enter key for Text Example

HTML example code.

<!DOCTYPE html>
<html>
<body>

 <form id="myForm" action="MyBackEnd.aspx" method="post">

  <table>
    <tbody>
      <tr>
        <td>
          First name:  <input id="fn" type="text">
        </td>
        <td>
          Last Name:  <input id="ln" type="text" >
        </td>
      </tr>
    </tbody>
  </table>

  <input type=submit>

  <script>

   document.getElementById("myForm").onkeypress = function(e) {
    var key = e.charCode || e.keyCode || 0;     
    if (key == 13) {
      alert("No Enter!");
      e.preventDefault();
    }
  } 
</script>

</body>
</html>

Output:

Prevent form submission on Enter key press

JS stop form submit on enter

<button type="submit" onclick="submitButtonClick(event)">Submit</button>
<script>
function submitButtonClick(event) {
		event.preventDefault();
		//other stuff you want to do instead...
} 
</script>

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

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

OS: Windows 10

Code: HTML 5 Version

1 thought on “Prevent form submission on Enter key press | Example Code”

Leave a Reply

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