Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML textarea ignores 1st new line character, why?

Could you explain why this:

<script type="text/javascript">
   document.write("<textarea cols='10' rows='10'>" + "\nhello\nbabe\n" + "</textarea>");
</script>

renders a textarea with one new line at the bottom, but NO new line at the top?

enter image description here

Tested IE8, FF11, Safari 5.1, Chrome 24

And it's not a JS issue, even when you write HTML in page you get the same result, i.e.

<textarea cols='10' rows='10'>
hello
babe
</textarea>

The 1st new line is still missing!!!

I need to add another new line at the top in order to show one:

document.write("<textarea cols='10' rows='10'>" + "\n\nhello\nbabe\n" + "</textarea>");
like image 821
Marco Demaio Avatar asked Mar 20 '13 16:03

Marco Demaio


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 you add text to a new line in textarea?

The text area tag defines a multi-line text input control. The size of a text area can be specified by the cols and rows attributes. By default, whenever we press “enter” or “shift+enter” it creates a new line in the text area.

How do I preserve line breaks when getting text from a textarea?

If you want your text to overflow the parent's boundaries, you should use pre as your CSS whitespace property. Using white-space: pre wraps still preserves newlines and spaces. Enjoy!

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.


1 Answers

When writing inside of XHTML use proper entities.

<textarea>&#13;hello</textarea>

If a text node begins with white space (space, new line) it will be ignored by HTML parsers. Encoding the new line into a proper HTML entity forces the parser to acknowledge it.

&#13; == carriage return
like image 92
Louis Ricci Avatar answered Oct 03 '22 17:10

Louis Ricci