Get the Value of TextArea using the jQuery Val () Method

Syntax

$(selector).val()

Definition and Usage

The Val( ) method is known to set or return the value attributes of the selected elements. This method is mainly used with the HTML form of elements.

Two Arguments for this method consists of:

  • When it is used to Return the Value: The Val( ) method returns the value of the ‘Value Attribute’ of the first matched elements.
  • When this method is used to Set the Value: It sets the value of the ‘Value Attribute’ of ‘ALL’ matched elements.

You can use this script in HTML to derive the value of ‘TextArea’ using the Val( ) Method of jQuery. It can be understood with the help of the following example.

Example

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="utf-8">

<title>Get Value from Textarea in jQuery</title>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<script>

    $(document).ready(function(){

        $("button").click(function(){

            var comment = $.trim($("#comment").val());

            if(comment != ""){

                // Show alert dialog if value is not blank

                alert(comment);

            }

        });

        

    });

</script>

</head>

<body>

    <textarea id="comment" rows="5" cols="50"></textarea>

    <p><button type="button">Get Value</button></p>

    <p><strong>Note:</strong> Type something in the textarea and click the button to see the result.</p>

</body>

</html>

The Val( ) method helps in getting the values from the elements like ‘input’, ‘select’ and the ‘textarea’. The value of each field here can be attained with the help of jQuery. In the above example, the script involves the usage of the jQuery and the comment button to receive the value in the TextArea. Here the text is an actual text and not an HTML element and values retrieved from the ‘form elements’.

In the Val( ) method, if you are not applying any parameters then you will get the desired property as the result. In addition, if you want to set the property instead of call, then you need to specify an extra parameter.

However, you must remove any kind of leading whitespace or the trailing while writing this script. So, you do not get an unexpected result as an outcome. This example helps in showing the value in the TextArea by showing it in the alert dialog box with the click of the button when this appears not equal to “ “.

View Demo

Leave a Reply

Your email address will not be published. Required fields are marked *