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 form submission in input field.

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

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



Disable enter key on an input field

Disabling enter key for form

this is in pure JavaScript code, will block all enter key.

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

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

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

Do comment if you have any doubts and 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

Leave a Reply

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