Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The .val() of a textarea doesn't take new lines into account

The .val() property of an item in jQuery for a <textarea> doesn't seem to work with new lines. I need this function as the text-area is meant to recognize the enter key and display it as a preview, with the new line in tact.

However, what happens is shown in this fiddle: http://jsfiddle.net/GbjTy/1/. The text is displayed, but not in a new line.

How can I achieve the preview to include new lines, and I know it is possible, because it does this in the Stack Overflow Post Question preview.

Thanks.

P.S I have seen other links on SO relating to this, but they all say get the End User to use some code, which is not an ideal method for me. How can I achieve this without the End User writing any specific code, like here on SO Question Preview, where the Enter works as it should in the preview.

like image 805
H Bellamy Avatar asked Dec 12 '11 21:12

H Bellamy


People also ask

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 I insert a new line in HTML textarea?

<br/> is a line break in HTML.

Which character defines a new line in the textarea?

Talking specifically about textareas in web forms, for all textareas, on all platforms, \r\n will work.

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.


1 Answers

It's a CSS problem, not a JavaScript problem. HTML collapses white space by default — this includes ignoring newlines.

Add white-space: pre-wrap to the output div. http://jsfiddle.net/mattball/5wdzH/

This is supported in all modern browsers: https://caniuse.com/#feat=css3-tabsize

like image 108
Matt Ball Avatar answered Oct 14 '22 09:10

Matt Ball