views:

37

answers:

3

I have a HTML <textarea> that I want to be able to make when the user pushes enter in the textarea it results in a linebreak when the string is stored in a variable and printed on the page.

How would I do this? I have seen it done before but I am not sure how to do it.

A: 

Assuming you are outputting as HTML, you'll need to replace the line breaks with <br> or wrap the text with the <pre> tag.

The <pre> tag defines preformatted text.

Text in a pre element is displayed in a fixed-width font (usually Courier), and it preserves both spaces and line breaks.

RedFilter
+1  A: 

You should set the white-space property on your output to one of the pre values. See here for a list of allowed values and their effects: http://www.w3schools.com/CSS/pr_text_white-space.asp

<p style="white-space: pre;">Your text with newlines goes here.</p>

Or simply use <pre>, a HTML tag that has white-space: pre; by default, but this has the inconvenient of changing your font.

I would advise against storing <br />s instead of new line characters. If you want to have HTML breaks add them just to the output.

Alin Purcaru
+1  A: 

When you read the content of textarea just do this:

var text = document.getElementById(textAreaId).value.replace("\n","<br/>");

By this way, when you use the variable text, it will be able to break lines in html.

madeinstefano