Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
48
rated 0 times [  51] [ 3]  / answers: 1 / hits: 18159  / 11 Years ago, tue, april 23, 2013, 12:00:00

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, which 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);
});

More From » jquery

 Answers
29

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>




[#78692] Monday, April 22, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ryderalfonsos

Total Points: 655
Total Questions: 88
Total Answers: 91

Location: Nauru
Member since Thu, Feb 2, 2023
1 Year ago
ryderalfonsos questions
Mon, Sep 9, 19, 00:00, 5 Years ago
Wed, Feb 13, 19, 00:00, 5 Years ago
Tue, Feb 12, 19, 00:00, 5 Years ago
Fri, Dec 28, 18, 00:00, 6 Years ago
;