DEV Community

Ibrahim
Ibrahim

Posted on

How to Prevent Enter from Submitting a Form Input With Javascript

By default, when the Enter key is pressed in a form's input field, it will trigger the form to be submitted.

This behaviour can be prevented with JavaScript — here's how:

  1. Listen for key presses in the input using the keydown event.
  2. Check the key pressed by reading the key property of the event object.
  3. If the key is Enter, prevent the default behaviour (triggering form submit) by calling preventDefault method on the event object.

For example:

<form>
  <input type="text" placeholder="Type message" />
</form>

<script>
  document.querySelector('input')
    .addEventListener('keydown', (e) => {
      if (e.key === 'Enter') {
        e.preventDefault();
      }
    });
</script>
Enter fullscreen mode Exit fullscreen mode

This way, every time Enter is pressed in the form's input field, the form won't be submitted.

Top comments (0)