Clear the Value of a Textarea using JavaScript


Borislav Hadzhiev

Sat Jan 08 20221 min read


Photo by Kevin Lee

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.

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

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 = ''; });

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 element.

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

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

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