Borislav Hadzhiev
Wed Jan 05 2022·2 min read
Photo by Jason Blackeye
Use the value
property to get the value of a textarea, e.g.
const value = textarea.value
. The value
property can be used to read and set
the value of a textarea element. If the textarea is empty, an empty string is
returned.
Here is the HTML for the examples in this article.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <label for="message">Your message:</label> <textarea id="message" name="message" rows="5" cols="33"></textarea> <script src="index.js"></script> </body> </html>
And here is the related JavaScript code.
const message = document.getElementById('message'); // ✅ GET value of textarea console.log(message.value); // 👉️ "" // ✅ SET value of textarea message.value = 'Hello world!'; // ✅ Append to value of textarea message.value += ' Appended text.'; // ✅ get value of textarea on change message.addEventListener('input', function handleChange(event) { console.log(event.target.value); });
We used the value
property to get the value of a
textarea
element.
The property allows us to read and set the value of the textarea.
You can also use it to append text to the existing content of the textarea element.
const message = document.getElementById('message'); // ✅ Append to value of textarea message.value += ' Appended text.';
If you need to get the value of a textarea element every time it's changed by
the user, you need to add an input
event listener to the element.
const message = document.getElementById('message'); // ✅ get value of textarea on change message.addEventListener('input', function handleChange(event) { console.log(event.target.value); });
The input
event gets dispatched every time the user changes the value of the
textarea element.
If you open your browser's console you will see the new value of the textarea being logged on every keystroke.
In the example, we used the
target property
on the event
object. The target
property is a reference to the object
(element) on which the event was dispatched.
You can console.log
the target
property to see the DOM element on which the
event was dispatched.
const message = document.getElementById('message'); message.addEventListener('input', function handleChange(event) { console.log(event.target); console.log(event.target.value); });
If you open your browser's console, you will see the textarea
being logged
from the event.target
property.