W3docs

How to Get the Value of a Textarea using jQuery

Read this tutorial and learn useful information about how you can detect the value of the HTML <textarea> element easily using one of the jQuery methods.

Getting the value of the HTML <textarea> element can be achieved via the jQuery <kbd class="highlighted">val()</kbd> method. However, be sure to remove any trailing and leading whitespace; otherwise, it may cause unwanted results.

Add a button below the textarea to send the text to the server when it is clicked. You can get the text using the <kbd class="highlighted">val()</kbd> method. You should first get the textarea element by id (or any other method you desire) and then call the <kbd class="highlighted">val()</kbd> method on it.

Javascript jQuery show the textarea text

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the Document</title>
    <script src="https://code.jquery.com/jquery-3.5.0.min.js">
    </script>
  </head>
  <body>
    <p>Type in the textarea and click the button to see the result.</p>
    <textarea id="comment" rows="5" cols="40"></textarea>
    <div>
      <button type="button">Get Value</button>
    </div>
    <script>
      $(document).ready(function() {
          $("button").click(function() {
              let comment = $("#comment").val().trim();
              if(comment != "") {
                alert(comment);
              }
            });
        });
    </script>
  </body>
</html>

The val() Method

The <kbd class="highlighted">val()</kbd> method is a built-in jQuery method which is used to return or set the value of an attribute for the selected elements. This method applies to the HTML form elements. It is primarily used to get the values of form elements such as input, select and <kbd class="highlighted">textarea</kbd>. When the method is called on an empty collection, it will return undefined.