Skip to content

Submit the form on enter in JavaScript | Example code

  • by

You can submit the form by pressing the Enter key using JavaScript. For that use an event handler or hide the submit button for the user.

Submit the form on enter in JavaScript Examples

HTML example code.

Key event using JavaScript

Use the event handler to the keyup event using the addEventListener() method and use the KeyboardEvent.code property to determine whether an Enter key is pressed. Finally, trigger the form’s submit event on Enter keypress.

<!DOCTYPE html>
<html>
<body>
  <form>
    <label for="name">Enter your name: </label>
    <input type="text" name="name" id="name" required>
  </form>

  <script>
    document.getElementById('name')
    .addEventListener('keyup', function(event) {
      if (event.code === 'Enter')
      {
        event.preventDefault();
        document.querySelector('form').submit();
      }
    });
  </script>
</body>
</html>

Output:

Submit the form on enter in JavaScript

Using style=”display:none”

This way users with javascript disabled will still see the submit button and can click on it.

<!DOCTYPE html>
<html>
<body>
  <form action="" method="get">
    Name: <input type="text" name="name"/><br/>
    Pwd: <input type="password" name="password"/><br/>
    <div class="yourCustomDiv"/>
    <input type="submit" style="display:none"/>
  </form>
</body>
</html>

set the hidden attribute to true

<!DOCTYPE html>
<html>
<body>
  <form name="loginBox" target="#here" method="post">
    <input name="username" type="text" /><br />
    <input name="password" type="password" />
    <input type="submit" hidden="true" />
  </form>

</body>
</html>

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

Leave a Reply

Your email address will not be published. Required fields are marked *