Signup/Sign In
LAST UPDATED: JULY 7, 2021

How to get Textarea Value in jQuery?

Answer: By using the jQuery val() Method

One of the many ways to take user input in HTML is by using a textarea. HTML provides the textarea tag to allow users to provide lengthy text input, which is not possible if we use the input tag with type text.

jQuery makes it easier than Javascript to get the value from a textarea. In jQuery, we use the val() method to get the value from any HTML element taking user input.

If the HTML code for the textarea is the following:

<textarea></textarea>

Where you are not using any attribute, then in jQuery, all you have to do is:

// value of textarea tag
let valueOfTA = $("textarea").val();

In the above code, we are referencing the textarea by its tag name, which is textarea, and then we have used the val() function to get the value. See how easy it is.

For Textarea with class Attribute

If you are using a class attribute in the textarea tag and want to get the value using that class attribute, then it can be done as follows.

HTML Code:

<textarea class="myText"></textarea>

jQuery Code:

// value of textarea tag
let valueOfTA = $(".myText").val();

This is good practice too, to name the tag and then use it to select the tag in Javascript or jQuery. The dot operator is used along with the class attribute name, just like we do when we write CSS.

For Textarea with id Attribute

If you are using an id attribute in the textarea tag and want to get the value using that id attribute, then it can be done as follows.

HTML Code:

<textarea id="myText"></textarea>

jQuery Code:

// value of textarea tag
let valueOfTA = $("#myText").val();

Conclusion:

See how simple it is to get the value from a textarea. And now you know 3 different ways of doing it. We would recommend to use the third approach as that way you provide a unique name to your textarea, because only a single HTML element should be present in an HTML document with one id attribute value, whereas multiple HTML tags with same class name can be present in one HTML page.

Hence using the id attribute makes it unique and hence less error.



About the author:
I like writing content about C/C++, DBMS, Java, Docker, general How-tos, Linux, PHP, Java, Go lang, Cloud, and Web development. I have 10 years of diverse experience in software development. Founder @ Studytonight