In this tutorial we will learn how to Set Textarea Value with JavaScript. We can use JavaScript value property along with getElementById() method to set the value of textarea element.
Table of Contents
value property
value property sets or returns the value of HTML input tags or form elements.
In this example we have used value property to set the value of textarea tag.
getElementById() method
getElementById() method selects or targets the HTML tag by it's id.
In this example getElementById() method is used to select the textarea element.
HTML Code
HTML Code is given below, in this code we have a textarea element and a button tag with onclick event.
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Set Textarea Value</title>
</head>
<body>
<textarea id="textarea"></textarea>
<button onclick="setTextareaValue()">Set Textarea Value</button>
<script src="script.js"></script>
</body>
</html>
JavaScript Code
Take a look at the JavaScript code, In this code user defined function setTextareaValue() will set the value of textarea.
getElementById() method is used to target textarea tag.
value property will set the value of textarea.
The value we used is stored in variable.
<script>
function setTextareaValue()
{
var textarea = document.getElementById('textarea');
var value = 'New Value';
textarea.value = value;
}
</script>
Set Dynamic Value of Textarea
To apply the dynamic value we can add input tag to the code and get the value from user through this tag and then set this value to textarea tag.
See the example below to set the dynamic value to textarea tag.
<script>
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Set Textarea Dynamic Value</title>
</head>
<body>
<textarea id="textarea"></textarea>
<br><br>
<input type="text" placeholder="Enter Value" id="value">
<br><br>
<button onclick="setTextareaValue()">Set Textarea Value</button>
<script>
function setTextareaValue()
{
var textarea = document.getElementById('textarea');
var value = document.getElementById('value').value;
textarea.value = value;
}
</script>
</body>
</html>
</script>
Demo
Video Tutorial
Watch video tutorial on How To Set Textarea Tag Value using JavaScript.