How To Get Textarea Value In Javascript

In this article, we’ll explore how to retrieve the value entered into a textarea element, in a simple and straightforward manner.

Understanding Textareas

Before we dive into JavaScript, it’s important to grasp the basics of textarea elements. These are HTML elements used to create multi-line text input fields, typically used for comments, descriptions, or any lengthy user input.

<textarea id="myTextarea"></textarea>

In this example, we have a textarea element with the id “myTextarea.”

Accessing the Textarea Element

To get the value entered into a textarea using JavaScript, we first need to access the element. We can do this by using the getElementById() method or querySelector() method.

Using getElementById()

const textarea = document.getElementById("myTextarea");

Using querySelector()

const textarea = document.querySelector("#myTextarea");

Both methods achieve the same result; they give us a reference to the textarea element.

Retrieving the Value

Now that we have a reference to the textarea element, we can retrieve the value entered by the user. We use the value property of the textarea element to access this text.

const textareaValue = textarea.value;

The textareaValue variable now contains the text entered by the user in the textarea element.

Practical Example

Let’s put it all together in a practical example. Imagine you have a textarea element and a button to retrieve its value.

<textarea id="myTextarea"></textarea>
<button onclick="getTextareaValue()">Get Value</button>
<p id="result"></p>

We have a textarea with the id “myTextarea,” a button with an onclick attribute calling the getTextareaValue() function, and a paragraph with the id “result” where we’ll display the value.

Now, here’s the JavaScript function to retrieve and display the textarea value:

function getTextareaValue() {
    const textarea = document.getElementById("myTextarea");
    const resultParagraph = document.getElementById("result");
    
    const textareaValue = textarea.value;
    resultParagraph.textContent = "Textarea Value: " + textareaValue;
}

When you click the “Get Value” button, the text you entered in the textarea will appear below it.

author's bio photo

Hi there! I am Avic Ndugu.

I have published 100+ blog posts on HTML, CSS, Javascript, React and other related topics. When I am not writing, I enjoy reading, hiking and listening to podcasts.