Xavio Xavio - 4 months ago 15
jQuery Question

Copy from textarea to div, preserving linebreaks

I've got a

<textarea>
and a
<div>
(with a
<p>
inside).
When entering text into the area, the
<p>
gets updated with the content upon keyUp.

Is there a way to preserve linebreaks (new line) from the textarea and somehow get them to work like linebreaks in the div/p?

Replacing double "new line" with
</p><p>
, is that possible as well? This is close to what a wysiwyg would handle, but don't want that for this, wich is a very small project.




This is what I've got so far.

$(".box textarea").keyup(function () {
var value = $(this).val();
$('.box p').text(value);
});

Answer

You can simply do this:

$('.box textarea').keyup(function() {
    var value = $(this).val().replace(/\n/g, '<br/>');
    $(".box p").html(value);
});

This will replace all the line breaks \n in your textarea element and replace them all with html <br/> tag, so that you can preserve the line breaks in your textarea inside <p> tag element also.

Simple Demo Here:

$('.box textarea').keyup(function() {
  $(".box p").html(this.value.replace(/\n/g, '<br/>'));
});
textarea,p {
  width: 90%;
  height: 80px;
}
p {
  border: 1px solid #eee;
  padding: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="box">
  <textarea></textarea>
  <br/>
  <p></p>
</div>

If you can make changes to your css files, then you can also try the below solutions as suggested by @Explosion Pills. Even though you will have to still use the jquery code here to add the textarea entered text to p tag on keyup event like:

$('.box textarea').keyup(function() {
  $(".box p").html(this.value);  // replace is not needed here
});
textarea,p {
  width: 90%;
  height: 80px;
}
p {
  border: 1px solid #eee;
  padding: 5px;
  white-space: pre; // <--- This is the important part
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="box">
  <textarea></textarea>
  <br/>
  <p></p>
</div>