简体   繁体   中英

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>

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>

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");

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']");

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> 

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM