We can clear a textarea field using JavaScript easily by making use of the value property. We simply need to set the value of the textarea field to an empty string.

document.getElementById("textarea1").value = "";

Let’s see a quick example of this below:


Let’s say we have the following HTML:

The textarea field in the example above will have the text “This is some default text.”. If we want to clear the textarea in the example above, we would use the following JavaScript code:

document.getElementById("userText").value = ""

We can also clear a textarea field easily using jQuery by making use of the jQuery val() method.

Let’s do an interactive example of clearing a textarea field below.

Using JavaScript to Clear a Textarea Field with a Click

Below we will have a simple textarea field. It will start prefilled with some text from our about page. We will then let the user clear the textarea.

Here is our simple HTML:

Clear textarea field above

We will simply use the value property to set the textarea field to an empty string. We will need to put this code in a function that we call when the user clicks the button below the textarea field.

We will add an onclick event to our button below the textarea field that will call our function.

Here is the JavaScript function:

function clearTextarea(){
  document.getElementById("userText").value = "";
};

The final code and output for this example of how to clear a textarea field using JavaScript is below:

Code Output:

Clear textarea field above

Full Code:

Clear textarea field above
 

Getting the Value From an Textarea Field Using JavaScript

To get the value from a textarea field, we can once again use the value property.

Let’s say we have the following HTML:

To get the value from the textarea field, we would use the value property.

var textareaText = document.getElementById("userText").value;

Hopefully this article has been useful to help you understand how to clear a textarea in JavaScript.

Categorized in:

JavaScript,

Last Update: April 1, 2024