To get the value from a textarea field in JavaScript, we can use the value property. We can also use the value property to set the value of a textarea field.
var userInput = document.getElementById("textarea1").value;
Let’s say we have the following HTML:
<form>
<label for="desc">Description:</label>
<textarea type="text" id="desc" name="desc"></textarea>
<button type="submit" value="Submit">Submit</button>
</form>
To get the value that the user has entered for “Description”, we would use the value property.
document.getElementById("desc").value;
This can also be done using jQuery with the val() method.
Using JavaScript to Get and Set a Textarea Value
In this example, we will have a form that will display the information of a user. We will then let the user update one of the fields by using a textarea field and submit button below it.
Here is the HTML setup:
<form id="form-1">
<label for="username">Username:</label>
<input type="text" id="username" name="username" value="theprogrammingexpert" disabled>
<label for="pass">Password:</label>
<input type="password" id="pass" name="password" value="password" disabled>
<label for="desc">Bio:</label>
<textarea type="text" id="desc" name="desc" disabled>This is where text would go to describe your profile.</textarea>
</form>
<div id="div1">
<label for="newbio">Change bio:</label>
<textarea type="text" id="new-bio" name="newbio"></textarea>
<div id="click-me" onclick="updateBio()">Update</div>
</div>
In the JavaScript code below, we will get the new user textarea value using the value property, and then set the textarea value “Bio” in the form above using the value property again along with the getElementById method.
Here is the JavaScript code for getting and setting the textarea value:
function updateBio(){
var userInput = document.getElementById("new-bio").value;
document.getElementById("desc").value = userInput;
};
The final code and output for this example of using JavaScript to get and set the value in a textarea field is below:
Code Output:
Full Code:
<form id="form-1">
<label for="username">Username:</label>
<input type="text" id="username" name="username" value="theprogrammingexpert" disabled>
<label for="pass">Password:</label>
<input type="password" id="pass" name="password" value="password" disabled>
<label for="desc">Bio:</label>
<textarea type="text" id="desc" name="desc" disabled>This is where text would go to describe your profile.</textarea>
</form>
<div id="div1">
<label for="newbio">Change bio:</label>
<textarea type="text" id="new-bio" name="newbio"></textarea>
<div id="click-me" onclick="updateBio()">Update</div>
</div>
<script>
function updateBio(){
var userInput = document.getElementById("new-bio").value;
document.getElementById("desc").value = userInput;
};
</script>
Hopefully this article has been useful to help you understand how to use JavaScript to get the value from a textarea field.
Leave a Reply