Set Value of TextArea in jQuery

Learn, how to set the value of the input text area in jQuery?
Submitted by Pratishtha Saxena, on December 18, 2022

Using .val() Method

When we need to deal with the values of any element, we consider the usage of the .val() method in jQuery. It allows us to set or get the values of the specified element in the document.

Syntax:

$(selector).val('set text'); // set the value
$(selector).val(); // get the value

This is a simple method that does not take any parameters for returning the value of the selected element but requires a string of text in order to set the appropriate value to the selected element.

Hence, in order to set the value of the text area in jQuery, we'll be using the .val() method. The value to be displayed is already defined in form of a string to a particular variable. This variable is then passed to the .val() method which displays that text in the input text area.

This can be used when you want to set the value of a particular field based on some other field when selected. This means that if we consider a form where the user fills up the option 'female' as her gender, then the upcoming field will automatically get filled by 'Ms'.

The example given below shows that the value of the text area is set when the user clicks the provided button.

jQuery code to set value of textarea

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <title>Document</title>
  </head>
  
  <body>
    <h2>Set Value of Textarea in jQuery</h2>
    <h4>Click the button in order to set a predefined value to the text box.</h4>
    <button>Set Value</button>
    <hr>
    <h3>Welcome to Include Help !!!</h3>
    <p>This is a jQuery Tutorial.</p>
    <input type="text" style="width: 300px;">
    <h3>Thank You for Visiting !!!</h3>
    <hr>
  </body>
  
  <script type="text/javascript">
    $(document).ready(function(){
        var setTextValue = 'Learning how to set value to Text Area.'
        $('button').click(function(){
            $('input').val(setTextValue);
        });
    });
  </script>
</html>

Output:

Example: Set Value of TextArea in jQuery




All jQuery Examples

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.