Categories
JavaScript Answers

How to detect when the user presses Enter in an input field with JavaScript?

Spread the love

Sometimes, we want to detect when the user presses Enter in an input field with JavaScript.

In this article, we’ll look at how to detect when the user presses Enter in an input field with JavaScript.

How to detect when the user presses Enter in an input field with JavaScript?

To detect when the user presses Enter in an input field with JavaScript, we check the key code.

For instance, we write

const inputId = document.getElementById("input-id");
inputId.addEventListener("keyup", (e) => {
  if (e.keyCode === 13) {
    console.log("Enter");
  }
});

to get the input with getElementById.

Then we add a keyup event listener to it with addEventListener.

In the event listener, we check if enter is pressed by checking if keyCode is 13.

Conclusion

To detect when the user presses Enter in an input field with JavaScript, we check the key code.

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 *