66

I have a little issue related to when I place a text loaded via ajax call.

I take the contect from a textarea and store it in my database and when I want to show the text in a div, it doesn't respect the new lines, so all the text is continuous.

The following code show a small example:

$(function() {
    $('.buttonA').click(function() {
        $('.message').html($('textarea[name="mensaje"]').val());
    });
});
.message {
    width:300px;
    height:200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<textarea name="mensaje" class="new_message_textarea" placeholder="enter message..."></textarea>
<button class="buttonA">Enter</button>
<div class="message"></div>

If you type some text with some new lines, once you click on the button, the text is show into the div and will see that new lines are not show.

How can I solve this?

Donald Duck
  • 8,409
  • 22
  • 75
  • 99
domoindal
  • 1,513
  • 2
  • 17
  • 33

3 Answers3

164

I think a better way to achieve this is to add

white-space: pre

or

white-space: pre-wrap

style to your div.

See: HTML - Newline char in DIV content editable?

AlexSp3
  • 2,201
  • 2
  • 7
  • 24
Chris.Zou
  • 4,506
  • 6
  • 31
  • 38
33

Add this to the CSS:

white-space: pre-line
AlexSp3
  • 2,201
  • 2
  • 7
  • 24
Cong Lance
  • 341
  • 3
  • 2
  • This should be the correct answer, others don't change line when text arrives to the end of the container. Thanks – Hugo May 25 '18 at 06:48
  • 1
    This removes all consecutive spaces. It's not always desired. https://developer.mozilla.org/en-US/docs/Web/CSS/white-space#Values – emil.c Oct 04 '18 at 12:56
16

Newline characters don't do any thing to html rendering. Change this in your js:

$('.message').html($('textarea[name="mensaje"]').val());

...to this:

$('.message').html($('textarea[name="mensaje"]').val().replace(/\n/g, "<br />"));

...and it will replace your newlines with a proper html line break

JoeCortopassi
  • 5,083
  • 7
  • 37
  • 65
  • 1
    yes, i know, but system do not let me do it now, it need several minutes. i will do it.... of course!! – domoindal Jul 10 '12 at 23:21