Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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, 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);
});
like image 566
Xavio Avatar asked Apr 23 '13 09:04

Xavio


People also ask

How do I preserve line breaks when getting text from a textarea?

To preserve line breaks when getting text from a textarea with JavaScript, we can replace whitespace characters with '<br>\n' . const post = document. createElement("p"); post. textContent = postText; post.

How save user entered line breaks from textarea to database?

Just put the output text between <pre></pre> tags, that will preserve the line breaks.

How do you keep a line break in HTML?

The <pre> tag defines preformatted text. Text in a <pre> element is displayed in a fixed-width font, and the text preserves both spaces and line breaks. The text will be displayed exactly as written in the HTML source code.

How add BR tag to textarea?

To add line breaks to a textarea, use the addition (+) operator and add the \r\n string at the place where you want to add a line break, e.g. 'line one' + '\r\n' + 'line two' . The combination of the \r and \n characters is used as a newline character.


1 Answers

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.

like image 77
Explosion Pills Avatar answered Oct 05 '22 12:10

Explosion Pills