简体   繁体   English

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

[英]Javascript append text to textarea with line break

I have a button that the user can click to merge text from 2 textareas but when they click it the text from the second textarea is added to the end of the first so it is displayed in one line. 我有一个按钮,用户可以单击以合并来自2 textareas的文本,但是当他们单击它时,第二个textarea中的文本被添加到第一个文本区域的末尾,因此它显示在一行中。 I would like to add a line break to the end line of text so the appended text is on a new line. 我想在文本的结束行添加换行符,以便附加的文本在新行上。

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

在属性事件值的.value之前包含换行符

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

use this snippet as boilerplate. 使用此代码段作为样板。 first access the dom element values, then use it - write somewhere on document, or to an input.. 首先访问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> 

You could use \\n : 您可以使用\\n

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

Hope this helps. 希望这可以帮助。

 textarea{ height: 100px; } 
 <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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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