Javascript使用换行符将文本附加到textarea

时间:2016-12-26 18:07:53

标签: javascript

我有一个按钮,用户可以单击该按钮合并来自2个textareas的文本,但是当他们单击它时,第二个textarea中的文本将添加到第一个文本区域的末尾,因此它将显示在一行中。我想在文本的结束行添加换行符,以便附加的文本在新行上。

<input type="button" 
       class="copy_submit" 
       value="<< Copy"
       onclick="document.forms['merge_form'].notes1.value += document.forms['merge_form'].notes2.value;" />

3 个答案:

答案 0 :(得分:1)

.value之前的属性事件值

中包含换行符
<input type="button" class="copy_submit" onclick="document.forms['merge_form'].notes1.value += '\n' + document.forms['merge_form'].notes2.value;" value="<< Copy" />

答案 1 :(得分:1)

使用此代码段作为样板。 首先访问dom元素值,然后使用它 - 在文档上的某处写入,或者输入到输入..

document.querySelector('button').addEventListener('click', function(){
  var ta1Text = document.getElementById('ta_1').value;
  var ta2Text = document.getElementById('ta_2').value;
  var res = ta1Text + "\n"+ta2Text;
  document.getElementById('ta_3').value = res
});
<textarea id="ta_1">
</textarea>
<textarea id="ta_2">
</textarea>
<textarea id="ta_3">
</textarea>   
<button>Merge</button>

答案 2 :(得分:1)

您可以使用\n

document.forms['merge_form'].notes1.value += '\n'+ document.forms['merge_form'].notes2.value;

希望这有帮助。

&#13;
&#13;
textarea{
  height: 100px;
}
&#13;
<form name='merge_form'>
  <textarea name="notes1">Textarea 1 content</textarea>

  <input type="button" class="copy_submit" onclick="document.forms['merge_form'].notes1.value += '\n'+ document.forms['merge_form'].notes2.value;" value="<< Copy" />

  <textarea name="notes2">Textarea 2 content</textarea>
</form>
&#13;
&#13;
&#13;

相关问题