Submit the form on enter in JavaScript | Example code

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

Submit form on enter in JavaScript Examples

HTML example code.

Key event using JavaScript

Use 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 and 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

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