Skip to content

Disable enter key on an input field in JavaScript | Example code

Use the key event to textarea where it should not be possible to input line breaks or submit by pressing the enter key. If matched enter key then uses event.preventdefault. Don’t forget to use the keydown/keypress event instead of the click event

How to disable enter key on input field examples in JavaScript

HTML example code.

Disable enter key on specific textboxes

The prevent default, stops from submission in the input field.

<!DOCTYPE html>
<html>
<body>
  <form id="my-form">
    <input type="text" id="myInputID">
    <button type="submit" onclick="submit()">Submit</button>
  </form>

  <script>
    var el = document.getElementById("myInputID");
    el.addEventListener("keypress", function(event) {
      if (event.key === "Enter") {
        alert(event.key  + " " + event.which);
        event.preventDefault();
      }
    });

  </script>
</body>
</html>

Output:

Disable enter key on an input field

Disabling enter key for the form

In pure JavaScript code, and will block all enter keys.

document.addEventListener('keypress', function (e) {
            if (e.keyCode === 13 || e.which === 13) {
                e.preventDefault();
                return false;
            }
            
        });

If you want to prevent Enter key for a specific textbox then use inline JS code.

<input type="text" onkeydown="return (event.keyCode!=13);"/>

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

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 “Disable enter key on an input field in JavaScript | Example code”

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading