Get the Value of a Textarea using JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

Get the Value of a Textarea using JavaScript #

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.

index.html
<!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.

index.js
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); });

get value of textarea

We used the value property to get the value of a textarea element.

The value 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.

index.js
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 changes, add an input event listener to the element.

index.js
const message = document.getElementById('message'); // ✅ get value of textarea on change message.addEventListener('input', function handleChange(event) { console.log(event.target.value); });

on change get value of textarea

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.

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.

index.js
const message = document.getElementById('message'); message.addEventListener('input', function handleChange(event) { console.log(event.target); console.log(event.target.value); });

get textarea and its value

If you open your browser's console, you will see the textarea being logged from the event.target property.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.