How to Set Textarea Value in JavaScript
This article shows how to set the <textarea>
value using pure JavaScript.
What Is a <textarea>
in HTML
The HTML element <textarea>
represents a useful multi-line text editing control when you want to allow users to enter a large amount of free text as a comment on an evaluation or feedback module.
<textarea>
provides several features.
- An
id
attribute allows<textarea>
to be associated with a<label>
element for accessibility purposes. - A
name
attribute to specify the name of the associated data item that will be sent to the server when the form is submitted. - A
row
andcolumn
attribute allow you to specify an exact size that<textarea>
should take up. Setting these preferences is a good idea for consistency, as browser defaults may differ. - Default content inserted between opening and closing tags. The
<textarea>
does not support thevalue
attribute.
The <textarea>
element also accepts several common attributes to form <input>
’s, such as autocomplete
, autofocus
, disabled
, wildcard
, read-only
, and required
.
Set the <textarea>
Value in JavaScript
The getElementById()
is an integrated document method provided by JavaScript that returns the element object whose id matches the specified id.
Syntax:
getElementById($id)
The $id
is a mandatory parameter that specifies the id of an HTML attribute that must match. It returns the corresponding DOM element object if the corresponding element is found; otherwise, it returns null.
Now, let’s extract the text area node element using getElementById()
.
<textarea id="address" name="address">Please Fill the address</textarea>
<button id="btn" onclick="clearValue()">Click to clear</button>
function clearValue() {
document.getElementById('address').value = '';
}
In the above code, we use getElementById
to find the text area element present in the DOM. After clicking the clear
button, the text area node is found.
Update the value property with the desired value.
Now let’s run the above code and click on the button to remove the value of the text area. It will remove the text area’s value and look something like this.
<textarea>
before:
<textarea>
after:
Shraddha is a JavaScript nerd that utilises it for everything from experimenting to assisting individuals and businesses with day-to-day operations and business growth. She is a writer, chef, and computer programmer. As a senior MEAN/MERN stack developer and project manager with more than 4 years of experience in this sector, she now handles multiple projects. She has been producing technical writing for at least a year and a half. She enjoys coming up with fresh, innovative ideas.
LinkedIn