Preserve newlines when setting html in a div from

2019-03-04 09:39发布

I got this little html -:

<div id="viewOne"></div>
<textarea id="viewTwo"></textarea>
<button id="copyToDiv" value="Copy to Div"></button>

This is my Jquery snippet-:

$("#copyToDiv").on("click",function(){ $("#viewOne").html( $("#viewTwo").val() ) });

But it strips of new line characters from textarea's val and what i get is string with new lines stripped off. How do I preserve newlines when setting the html of div. Thanks a lot for help :)

1条回答
放荡不羁爱自由
2楼-- · 2019-03-04 09:43

The new lines are preserved, but not converted to HTML new lines (<BR/>), so they are ignored.

You can convert them to <BR/> with .replace:

$("#copyToDiv").on("click",function(){ $("#viewOne").html( $("#viewTwo").val().replace("\n","<br/>") ) });
查看更多
登录 后发表回答