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>

 <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 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 *