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>

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

          First name:  <input id="fn" type="text">
          Last Name:  <input id="ln" type="text" >

  <input type=submit>


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



Prevent form submission on Enter key press

JS stop form submit on enter

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

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.