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 on 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 nay doubts and suggestions with example 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


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.