How to run a function on pressing the enter key in an input field?

Sometimes, we want to run a function on pressing the enter key in an input field.

In this article, we’ll look at how to run a function on pressing the enter key in an input field.

How to run a function on pressing the enter key in an input field?

To run a function on pressing the enter key in an input field, we can listen to the keydown event.

And in the keydown event handler, we can check the key that’s pressed with the key property.

For instance, we write:

<input id='wage'>

to add an input element.

Then we write:

const wage = document.getElementById("wage");

const validate = (e) => {
  const text = e.target.value;
  console.log(text)
  //validation of the input...
}
wage.addEventListener("keydown", (e) => {
  if (e.key === "Enter") {
    validate(e);
  }
});

to select the input element with document.getElementById and assign it to wage.

Then we add the validate function that takes the e event object and get the input value with the e.target.value property.

Then we call addEventListener on wage with 'keydown' to add a keydown event listener.

Inside the event listener function, we check if the enter key is pressed with the e.key property.

If it’s true, then we run validate.

Conclusion

To run a function on pressing the enter key in an input field, we can listen to the keydown event.

And in the keydown event handler, we can check the key that’s pressed with the key property.