Categories
JavaScript Answers

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

Spread the love

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.

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 *