Borislav Hadzhiev
Last updated: Jul 25, 2022
Check out my new book
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.
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.
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.