Clear a Textarea on Button click using JavaScript

avatar

Borislav Hadzhiev

Last updated: Jan 8, 2022

banner

Photo from Unsplash

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.

index.html
<!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.

index.js
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.
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.