Last updated: Mar 5, 2024
Reading timeยท2 min

To clear the value of a textarea element, set its 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.
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>bobbyhadz.com</title> </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 the 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.
value property can be used to get or set the value of the textarea element.const textarea = document.getElementById('message'); // โ Clear the textarea value textarea.value = '';
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 a
click event listener to the button element.
const textarea = document.getElementById('message'); const btn = document.getElementById('btn'); btn.addEventListener('click', function handleClick() { // ๐๏ธ log value before clearing it console.log(textarea.value); // ๐๏ธ clear textarea value textarea.value = ''; });

The handleClick function from the example gets invoked every time the button
is clicked.
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.
On each button click, we set the value property of the textarea element to
an empty string to clear it.
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.