Categories
JavaScript Answers

How to submit form on enter key press with JavaScript?

Spread the love

Sometimes, we want to submit form on enter key press with JavaScript.

In this article, we’ll look at how to submit form on enter key press with JavaScript.

How to submit form on enter key press with JavaScript?

To submit form on enter key press with JavaScript, we can listen for the keydown event.

For instance, we write:

<form>
  <input>
</form>

to add a form.

Then we write:

const input = document.querySelector('input')
input.onkeydown = (e) => {
  if (e.keyCode === 13) {
    e.preventDefault()
    console.log('submit')
  }
};

to select the input with querySelector.

Then we set input.onkeydown to a function that checks if the key that’s pressed if the enter key.

We check that by checking if e.keyCode is 13.

Conclusion

To submit form on enter key press with JavaScript, we can listen for the keydown event.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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