Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the Content of a <textarea> with JavaScript

Tags:

javascript

People also ask

Is textarea editable?

By default, a textarea is editable. So you must have made something that make it uneditable.

Can I add value to textarea?

To add a value into a textarea, you can add to the value property of the input via document. getElementById. Reference this element and change the value: document.

Does textarea have value attribute?

<textarea> does not support the value attribute.

Can you style a textarea?

You can style text inside textarea similarly as you can do with any other HTML inputs. You can also use any CSS property like font-size , font-family , color , etc.


Like this:

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

or like this in jQuery:

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

Where you have

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

For all the downvoters and non-believers:

  • Here's the MSDN reference

    value Property: Retrieves or sets the text in the entry field of the textArea element.

  • Here's the MDN reference

    value DOMString The raw value contained in the control.


If you can use jQuery, and I highly recommend you do, you would simply do

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

Otherwise, it is browser dependent. Assuming you have

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

In most browsers you do

myTextArea.innerHTML = '';

But in Firefox, you do

myTextArea.innerText = '';

Figuring out what browser the user is using is left as an exercise for the reader. Unless you use jQuery, of course ;)

Edit: I take that back. Looks like support for .innerHTML on textarea's has improved. I tested in Chrome, Firefox and Internet Explorer, all of them cleared the textarea correctly.

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


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

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

where in the HTML your textarea is nested somewhere in a form like this:

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

And as it happens, that would work with Netscape Navigator 4 and Internet Explorer 3 too. And, not unimportant, Internet Explorer on mobile devices.


If it's jQuery...

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

or

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

Reference: Text Area Object