Categories
JavaScript Answers

How to detect if the enter key is pressed in a textarea?

Spread the love

Sometimes, we want to detect if the enter key is pressed in a textarea.

In this article, we’ll look at how to detect if the enter key is pressed in a textarea.

How to detect if the enter key is pressed in a textarea?

To detect if the enter key is pressed in a textarea, we can listen for the keypress event and check if the enter key is pressed there.

For instance, we write:

<textarea></textarea>

to add a textarea.

Then we write:

const textarea = document.querySelector('textarea')
textarea.onkeypress = (event) => {
  const keyCode = event.keyCode
  if (keyCode === 13) {
    console.log('enter pressed')
  }
}

to select the text area with document.querySelector('textarea').

Next, we set textarea.onkeypress to the keypress event handler function.

We check if event.keyCode is 13 in the function.

If it is, then the enter key is pressed.

Conclusion

To detect if the enter key is pressed in a textarea, we can listen for the keypress event and check if the enter key is pressed there.

Leave a Reply

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