开发者

How do you make linebreaks in a HTML textarea result in breaks in the string?

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 n开发者_如何学JAVAot sure how to do it.


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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜