Open In App

How to get the value of a textarea in jQuery ?

Last Updated : 19 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

To get the value of a textarea in jQuery, you can use the val() method. This method is commonly used to retrieve the current value of form elements like textarea, input, and select. It works by either retrieving or setting the value of the selected element. If no input is provided, the method returns undefined or an empty string.

Here’s an example of how you can get the value from a textarea element when a button is clicked.

HTML and jQuery:

HTML
<!DOCTYPE html>
<html>
    <head>
        <title>How to get the value of textArea</title>
        <script src=
"https://code.jquery.com/jquery-1.12.4.min.js">
        </script>
    </head>
    <body>
        <center>
            <h1 style="color: green;">GeeksforGeeks</h1>
            <textarea id="txtArea"></textarea><br><br>
            <button id="btn">Show Text</button>
        </center>
    </body>

    <script>
        $(document).ready(function () {
          
            //This function called when the button is clicked
            $("#btn").click(function () {
              
                // val() method is used to get the values from 
               // textarea and stored in txt variable
                var txt = $("#txtArea").val();
                alert(txt);
            });
        });
    </script>
</html>

Output:

How It Works:

HTML Structure: A textarea element is created with an ID of txtArea, and a button with an ID of btn.

jQuery Setup:

  • First, jQuery waits for the DOM to load using $(document).ready().
  • Then, it attaches a click event handler to the button (#btn).
  • When the button is clicked, the value of the textarea (#txtArea) is retrieved using the val() method and stored in the txt variable.
  • Finally, the value is displayed in an alert box.

jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”. You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples.



Next Article

Similar Reads