How to Set Textarea Value in JavaScript?
To set text area value in JavaScript, the following properties can be utilized:
The stated properties will now be explained one by one!
Approach 1: Set Textarea Value in JavaScript Using the textContent Property
This approach can be implemented to fetch the allocated text and set it accordingly.
The following example illustrates the stated concept.
Example
Firstly, specify the “id” and “name” corresponding to the following text within the “<textarea>” tag:
Next, create a button and attach an “onclick” event invoking the specified function:
After that, declare a function named “settextValue()”. In its definition, get the “id” of the text specified before. Finally, apply the “textContent” property and set the text value assigned before to the below-updated one:
document.getElementById('text').textContent= "This is JavaScript"
}
Output
Approach 2: Set Textarea Value in JavaScript Using the value Property
In this particular approach, the text area value can be set by fetching the specified value and assigning it a newly initialized value.
Example
In the following example, similarly include the following value within the text area having the specified “id”:
Likewise, create the following button having an “onclick” event redirecting to the function setTextValue():
Now, define the function named “settextValue()”. Here, access the id of the specified text. In the next step, assign a new text value to the variable named “valueUpdate”.
Lastly, apply the “value” property upon the fetched text area value and assign it the new value as follows:
var textUpdate = document.getElementById('text');
var valueUpdate = 'Linuxhint';
textUpdate.value = valueUpdate;
}
Output
We have concluded the convenient approaches to set text area value in JavaScript.
Conclusion
The “textContent” property or the “value“ property can be applied to set the text area value in JavaScript. The former approach accesses the specified text area value and sets it abruptly. The latter approach, on the other hand, initializes a new text value and assigns it to the fetched text area value. We recommend you implement the first approach which includes overall less code complexity and is easy to implement as well. This article compiled the approaches that can be helpful to set the text area value in JavaScript.