Tanya Arora
Tanya Arora

Reputation: 113

Preserve newlines when setting html in a div from a textarea - Jquery

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 :)

Upvotes: 0

Views: 1599

Answers (2)

Karlsson
Karlsson

Reputation: 213

<div id="viewOne" style="white-space: pre-wrap;"></div>
<textarea id="viewTwo"></textarea>
<button id="copyToDiv" value="Copy to Div"></button>

white-space: pre-wrap; tells the element to preserve newline and other whitespace characters and actually answers this old question.

Upvotes: 0

Tasos Bitsios
Tasos Bitsios

Reputation: 2789

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/>") ) });

Upvotes: 2

Related Questions