Categories
JavaScript Answers

How to Detect the Pressing of the Enter key in a Text Input Field with JavaScript?

Spread the love

Sometimes, we want to detect the pressing of the enter key in our code and then do something when that happens.

In this article, we’ll look at how to detect the pressing of the enter key in a text input field with JavaScript.

Check the event.key Property

One way to check which key is pressed is to use the event.key property.

For instance, we can write the following HTML:

<input />

And the following JavaScript code to detect whether the Enter key is pressed:

const input = document.querySelector("input");
input.addEventListener("keyup", (event) => {
  if (event.key === "Enter") {
    console.log('Enter key pressed')
  }
});

We get the input element with the document.querySelector method.

Then we call addEventListener to add an event listener for the keyup event.

Then in the event handler, we check if the event.key property returns 'Enter' .

If it does, then the enter key is pressed.

Check the event.keyCode Property

Another property we can check is the event.keyCode property.

The keyCode property returns a number for the key that’s pressed instead of a string with the key name.

When it returns 13, then we know the enter key is pressed.

So we can write:

const input = document.querySelector("input");
input.addEventListener("keyup", (event) => {
  if (event.keyCode === 13) {
    console.log('Enter key pressed')
  }
});

to check if the key with key code 13 is pressed.

If it is, then we know the enter key is pressed.

Check the event.which Property

Like the event.keyCode property, the event.which property also returns the key code of the key that’s pressed.

For instance, we can write:

const input = document.querySelector("input");
input.addEventListener("keyup", (event) => {
  if (event.which === 13) {
    console.log('Enter key pressed')
  }
});

to do the same check with event.which .

And everything else should be the same as checking with the event.keyCode property.

Conclusion

There’re several properties that comes with input event objects that we can check to see which key is pressed to check whether the enter key is pressed.

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 *