How to change <textarea> content using Javascript

How do I change the contents of a <textarea> element with JavaScript?

I want to make it empty.

+82
javascript
Oct 29 '09 at 9:09
source share
5 answers

Like this:

 document.getElementById('myTextarea').value = ''; 

or like this in jQuery:

 $('#myTextarea').val(''); 

Where are you

 <textarea id="myTextarea" name="something">This text gets removed</textarea> 

For all descending and unbelievers:

+159
Oct 29 '09 at 9:12
source share

If you can use jQuery, and I highly recommend you do this, you just do

 $('#myTextArea').val(''); 

Otherwise, it is browser dependent. Assuming you have

 var myTextArea = document.getElementById('myTextArea'); 

In most browsers you

 myTextArea.innerHTML = ''; 

But in Firefox you do

 myTextArea.innerText = ''; 

Finding out which browser the user is using remains as an exercise for the reader. If you are not using jQuery, of course;)

Edit : I take it back. It appears that support for .innerHTML on textarea has improved. I tested in Chrome, Firefox and Internet Explorer, they all cleared the text box correctly.

Change 2 . And I just checked if you use .val ('') in jQuery, it just sets the .value property for textarea's. So the value should be good.

+13
Oct 29 '09 at 9:17
source share

Although many correct answers have already been given, the classic approach (read non-DOM) will be like this:

 document.forms['yourform']['yourtextarea'].value = 'yourvalue'; 

where in HTML your text area is nested somewhere in this form:

 <form name="yourform"> <textarea name="yourtextarea" rows="10" cols="60"></textarea> </form> 

And as it happens, it will work with Netscape Navigator 4 and Internet Explorer 3 too. And, no matter, Internet Explorer on mobile devices.

+7
Oct 29 '09 at 9:31
source share

If its jquery ..

 $("#myText").val(''); 

or

 document.getElementById('myText').value = ''; 

http://www.hscripts.com/tutorials/javascript/dom/textarea-events.php

+1
Oct 29 '09 at 9:11
source share

put the text box on the form, name them and just use dom objects, for example:

 <body onload="form1.box.value = 'Welcome!'"> <form name="form1"> <textarea name="box"></textarea> </form> </body> 
0
Apr 26 '17 at 1:08 on
source share



All Articles