Clear a Textarea on Button click using JavaScript


Borislav Hadzhiev

Sat Jan 08 20221 min read


Photo by Redd

Clear a Textarea on Button click using JavaScript #

To clear a textarea on button click:

  1. Add a click event listener to the button element.
  2. When the button is clicked, set the textarea's value to an empty string.

Here is the HTML for the examples in this article.

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <label for="answer">Your answer:</label> <textarea id="answer" name="answer" rows="7" cols="35"></textarea> <button id="btn">Clear textarea</button> <script src="index.js"></script> </body> </html>

And here is the related JavaScript code.

const textarea = document.getElementById('answer'); const btn = document.getElementById('btn'); btn.addEventListener('click', function handleButtonClick() { console.log(textarea.value); // ๐Ÿ‘‡๏ธ clear textarea value textarea.value = ''; });

We used the document.getElementById() method to get the textarea and button elements.

We added a click event on the button element.

Every time the button is clicked, the handleButtonClick function is invoked.

The click event is triggered when a user's mouse is pressed and released while the user's pointer is located inside the element or one of its children.

We used the value property to clear the value of the textarea element.

The value property can be used to get and set the value of the textarea element.

If you load the page from the example, write some text in the textarea and click on the button, the element's value is logged to the console and then cleared.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee