How to Display Data in Textarea Using Javascript?

This blog post will show how to display data in a textbox or textarea using javascript.

We have several methods to Change the contents of a text area:

HTML

<!DOCTYPE html>
<html>
    <head>
        <title>Display Data in Textarea</title>
    </head>
    <body>
       
                
    <textarea name="input_box" id="input_box" ></textarea> <br>
    
    <input type="button" value="Display Data" onclick="setValue()" />
   

    </body>
</html>

Javascript

 function setValue() {

        document.getElementById('input_box').value = "new value here";

    }

The getElementById() returns the element with the ID attribute with the specified value. The value property sets or returns the contents of a text area.

Method 2: Using setAttribute

    
<!DOCTYPE html>
<html>
    <head>
        <title>Display Data in Textarea</title>
    </head>
    <body>
       
                
       
    <input type="text" name="input_box"  id="input_box" value=""> <br>

    <input type="button" value="Display Data" onclick="setValue()" />
   

    </body>
</html>

   

Javascript

 function setValue() {
        document.getElementById("input_box").setAttribute('value', 'My value');
    }

Method 3: Display Data in the input box for multiple forms

If you are using multiple forms, you can use

HTML


   <!DOCTYPE html>
<html>
    <head>
        <title>Display Data in Textarea</title>
    </head>
    <body>
       
                
       
    <form name='myForm'>
         <input type='text' name='name' value=''> <br>
        <input type='text' name='email' value=''>
   </form>


   <input type="button" value="Display Data" onclick="setValue()" />
   

    </body>
</html>

Javascript


 function setValue() {
       document.forms['myForm']['name'].value = "New Name data";
       document.forms['myForm']['email'].value = "New Email";

    }