Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keep Line Breaks from Textarea [duplicate]

I am getting input from a user in a form via PHP in a WordPress site (an address specifically) and I want to be able to display the information that I gather with the same line breaks (separating out the different components of the address) on a different page. It displays correctly if I put it into a textarea, but if I get the data and echo it into a div by itself, it doesn't maintain the line breaks. What can I do?

like image 865
William Avatar asked Jun 04 '13 05:06

William


People also ask

How do I preserve line breaks in 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.

Does textarea support new line?

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. Here is the HTML for the examples in this article. Copied!

How do you preserve a new line in HTML?

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.

Can we use value attribute in textarea?

<textarea> does not support the value attribute.


1 Answers

you want to utilize the white-space css attribute http://www.w3schools.com/cssref/pr_text_white-space.asp

So you'll have something like

<p class="whitespace"><?= $input_from_textarea ?></p>

with css:

.whitespace { 
    white-space: pre-wrap; 
}

Do not manually clean your input replacing new line elements with break tags. It makes your data less reusable and is a lot more work.

You can use the php function nl2br() but it does not give you as much control as manipulating the display through css.

like image 65
Daniel Nill Avatar answered Sep 30 '22 20:09

Daniel Nill