Clear the Value of a Textarea using JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Check out my new book

Clear the Value of a Textarea using JavaScript #

To clear the value of a textarea element, set it's value property to an empty string, e.g. textarea.value = ''. Setting the element's value to an empty string removes any of the text from the element.

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="message">Your message:</label> <textarea id="message" name="message" rows="5" cols="33"></textarea> <button id="btn">Clear value</button> <script src="index.js"></script> </body> </html>

And here is the related JavaScript code.

index.js
const textarea = document.getElementById('message'); // ✅ Clear textarea value textarea.value = ''; // ✅ Clear textarea value on click const btn = document.getElementById('btn'); btn.addEventListener('click', function handleClick() { // 👇️ log value before clearing it console.log(textarea.value); // 👇️ clear textarea value textarea.value = ''; });

clear textarea value

We used the document.getElementById() method to select the textarea element.

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

By setting it to an empty string, we empty the field.

If you need to clear the value of a textarea when a button is clicked, add aclick event listener to the button element.

The handleClick function from the example gets invoked every time the button is clicked.

On each button click, we set the value property of the textarea element to an empty string to clear it.

Use the search field on my Home Page to filter through my more than 3,000 articles.