1

$("textarea").blur(function() {
  $("div").html($("textarea").val());
});

$("textarea").blur();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<textarea style="height:50px;">
1. test
2. test
3. test
</textarea>

<div style="word-break: break-all;"></div>

I would like to make the text appear in div in the exact manner as it appears in textarea.

I've tried to css div with word-break, etc. but none has worked.

Note: specifically, I just want to know how to do it within a div.

Stickers
  • 75,527
  • 23
  • 147
  • 186
user6332430
  • 442
  • 10
  • 29
  • Possible duplicate of [How do I replace all line breaks in a string with
    tags?](http://stackoverflow.com/questions/784539/how-do-i-replace-all-line-breaks-in-a-string-with-br-tags)
    – Nico Mar 08 '17 at 22:37
  • also, you could try using an event listener like `change` to update the `div` as the user types instead of waiting for the field to lose focus with `blur`. – Moose Mar 08 '17 at 22:38
  • @Moose ya i know that i just want my helpers to see the result instantly instead of putting something in themselves. – user6332430 Mar 08 '17 at 22:39
  • @Nico that question does not seem to be anywhere close to what im lookin for. – user6332430 Mar 08 '17 at 22:42
  • 1
    @Will one downfall of using `white-space:pre` is it will act as a pre tag. This formatting of long lines text will expand horizontally and will not break (word wrap). Now if thats the intention then fine. See this use case https://jsfiddle.net/yg9jv3o4/3/ – Nico Mar 08 '17 at 22:59
  • @Nico didn't realize that. thanks for the headsup. – user6332430 Mar 08 '17 at 23:04

2 Answers2

4

Try setting white-space:pre; or white-space:pre-wrap; to the div.

$("textarea").blur(function() {
  $("div").html($("textarea").val());
});

$("textarea").blur();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<textarea style="height:50px;">
1. test
2. test
3. test
</textarea>

<div style="white-space:pre;"></div>
Stickers
  • 75,527
  • 23
  • 147
  • 186
0

If you want them to be able to export it to HTML.

str = str.replace(/(?:\r\n|\r|\n)/g, '<br />');

Reference: How do I replace all line breaks in a string with <br /> tags?

Community
  • 1
  • 1
Neil
  • 14,063
  • 3
  • 30
  • 51