Copy from textarea to div, preserving linebreaks
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>
You probably want to add the CSS rule white-space: pre
or white-space: pre-wrap
to .box p
. This will display whitespace as-is.