HazeTek LLC
HazeTek LLC

Reputation: 55

Insert text into textarea

How would I insert text on page load into this text area:

<textarea name="orderNotes" cols="115" rows="3"></textarea>

I have attempted:

var myTextarea = document.getElementsByClassName('orderNotes');
console.log(myTextarea);
myTextarea.value += "text to add to the textarea";

HTML:

<textarea name="orderNotes" cols="115" rows="3"></textarea>

Upvotes: 1

Views: 1420

Answers (5)

Asaph
Asaph

Reputation: 162851

Your js code should work if you access the [0] element of the array returned by getElementsByTagName() and add a class attribute to your markup.

var myTextarea = document.getElementsByClassName('orderNotes')[0];
myTextarea.value += "text to add to the textarea";

<textarea name="orderNotes" class="orderNotes" cols="115" rows="3"></textarea>

But a safer approach would be to set an id attribute and access it with getElementById() instead of getElementsByClassName().

var myTextarea = document.getElementById('orderNotes');
myTextarea.value += "text to add to the textarea";

<textarea name="orderNotes" id="orderNotes" cols="115" rows="3"></textarea>

Upvotes: 2

Martin Slez&#225;k
Martin Slez&#225;k

Reputation: 181

document.getElementByClassName returns array of items as more object can share the class. So you should access it by its index (myTextarea[0].value - it you know it's the only element with this class) or better use id and access it with document.getElementById('id'):

javascript:

var myTextarea = document.getElementsById('orderNotes');
consol.log(myTextarea);
myTextarea.value += "text to add to the textarea";

html:

<textarea id="orderNotes" cols="115" rows="3"></textarea>

Upvotes: 0

edonbajrami
edonbajrami

Reputation: 2206

Basic example with Javascript:

var textArea = document.myform.inputtext.value;
textArea += "your text";
document.myform.inputtext.value = textArea;
<form name="myform">
<textarea name="inputtext"></textarea>
</form>

Upvotes: 2

Pointy
Pointy

Reputation: 414006

You haven't given your <textarea> any class at all, so .getElementsByClassName() won't be useful unless you do:

<textarea name="orderNotes" class="orderNotes">

Once you do that, you'll have to deal with the fact that .getElementsByClassName() returns a list of elements, not just one element.

var myTextarea = document.getElementsByClassName('orderNotes')[0];

That sets your variable to the first one found. If you want to identify that <textarea> uniquely, you can give it an id:

<textarea name="orderNotes" id="orderNotes">

and then use .getElementById() which returns just one element (or nothing):

var myTextarea = document.getElementById("orderNotes");

Upvotes: 2

Sterling Archer
Sterling Archer

Reputation: 22435

You're trying to select by a class name, which requires the use of the class html attribute. You can use querySelector here to get by attribute name.

var myTextarea = document.querySelector("textarea[name='orderNotes']");

Upvotes: 1

Related Questions