最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript append text to textarea with line break - Stack Overflow

programmeradmin4浏览0评论

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. 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;" />

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. 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;" />
Share Improve this question edited Dec 26, 2016 at 18:19 Zakaria Acharki 67.5k15 gold badges78 silver badges106 bronze badges asked Dec 26, 2016 at 18:07 tatty27tatty27 1,5545 gold badges37 silver badges74 bronze badges 1
  • Aren't we missing the HTML forms? <textarea> etc – roberrrt-s Commented Dec 26, 2016 at 18:10
Add a ment  | 

3 Answers 3

Reset to default 1

Include newline character before .value at attribute event value

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

You could use \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>

use this snippet as boilerplate. first access the dom element values, then use it - write somewhere on document, or to an input..

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>

发布评论

评论列表(0)

  1. 暂无评论