2015-11-09 111 views
1

我怎么会插在页面加载文本到文本区:插入文本到文本区域

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

我曾尝试:

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> 
+0

+0

属性'name'!='className' –

+0

确保您的元素在页面加载之前执行代码之前先呈现 – massquote

回答

1

你试图通过类名选择,这需要使用class html属性。您可以在这里使用querySelector来获取属性名称。如果你访问由getElementsByTagName()返回数组的元素[0]

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

你的js代码应该工作和class属性添加到您的标记。

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

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

但一个更安全的方法是设定一个id属性及与getElementById(),而不是getElementsByClassName()访问它。

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

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

你还没有给你<textarea>任何类,所以.getElementsByClassName()不会,除非你做有用:

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

一旦你这样做,你必须处理其实.getElementsByClassName()返回一个列表的元素,而不仅仅是一个元素。

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

将您的变量设置为找到的第一个变量。如果你想找出<textarea>独特的,你可以给它一个id:

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

然后用.getElementById()这只是一个元素(或没有)返回:

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

不能出错一个简单的ID。 :) –

1

基本例如用javascript:

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

+1

是的,你是对的@Pointy,我编辑了我的代码。日Thnx – edonbajrami

0

document.getElementByClassName返回更多对象可以共享类的项目数组。所以你应该通过索引来访问它(myTextarea [0] .value - 它你知道它是这个类的唯一元素),或者更好地使用id并通过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>