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);
});
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.
Just put the output text between <pre></pre> tags, that will preserve the line breaks.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With