最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - HTML textarea ignores 1st new line character, why? - Stack Overflow

programmeradmin5浏览0评论

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?

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>");

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?

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>");
Share Improve this question asked Mar 20, 2013 at 16:39 Marco DemaioMarco Demaio 34.4k33 gold badges131 silver badges161 bronze badges 2
  • did u try with <br> tag? – Ezhil V Commented Mar 20, 2013 at 16:41
  • 2 "\n" will not be treated as textarea value, but as html breakline – imclickingmaniac Commented Mar 20, 2013 at 16:49
Add a comment  | 

6 Answers 6

Reset to default 6

Answering the question "Why". This is specified in HTML 5 specification in the chapter that describes how DOM tree is created from tags found in a HTML document.

In the current HTML 5 living standard it is "12.2 Parsing HTML documents" > "12.2.6 Tree construction" > "12.2.6.4 The rules for parsing tokens in HTML content" > "12.2.6.4.7 The "in body" insertion mode".

(In HTML 5.2 the same section is numbered 8.2.5.4.7).

Scroll down for item "A start tag whose tag name is "textarea""

A start tag whose tag name is "textarea"
Run these steps:
1. Insert an HTML element for the token.
2. If the next token is a U+000A LINE FEED (LF) character token, then ignore that token and move on to the next one. (Newlines at the start of textarea elements are ignored as an authoring convenience.)
3. Switch the tokenizer to the RCDATA state.
...

The algorithm deals with LF characters only, because CR characters are handled earlier.

(Historically, looking into obsolete HTML 4.01 specification:
Its Chapter 17.7 "The TEXTAREA element" has an example that shows that text content for a textarea starts from a new line. Appendix B.3.1 Line breaks (informative) explains that such behaviour originates from SGML.)

A line break character before </textarea> end tag is not ignored nowadays, in HTML 5.

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

If possible, change your code to have the textarea pre-defined as html, then write the string like this instead:

HTML:

<textarea cols='10' rows='10' id='test'></textarea>

Script:

document.getElementById('test').innerHTML = '\nhello\nbabe\n';

That should preserve white-space. Optionally you can add a css rule:

textarea {
    white-space:pre;
    }

A fiddle to play with:
http://jsfiddle.net/RFLwH/1/

Update:

OP tested in IE8 which this does not work - it appear to be a limitation/bug with this browser. IE8 do actually use CR+LF if you manually insert a line-feed at the top, but when set programmatic this is completely ignored by the browser.

Add this to the html to do a test:

<span onclick="this.innerHTML = escape(document.getElementById('test').innerHTML);">
    Get textarea content
</span>

You can see the string returned is:

 %0D%0Ahello%20babe%20

meaning the CR+LF is there (the other line-feeds are converted to spaces - but inserting a space at the beginning does not help either). I guess there is nothing you can do about this behavior; the browser is obsolete (but unfortunately still widely used so this can be a problem for those users if this is essential).

It should be a \n\r at the top: document.write("<textarea cols='10' rows='10'>" + "\n\rhello\nbabe\n" + "</textarea>");

jsbin

Add a whitespace before the first "\n" like this :

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

or

<textarea cols='10' rows='10'> <!-- whitespace here -->
hello
babe
</textarea>

otherwise it won't work.


Update: Later in your server side, you can remove the first whitespace by doing

$str = ltrim ($str,' ');

or

$str2 = substr($str, 4);

if it is PHP.

Finally i finished with this server-side solution:

to double leading(only first!) nl symbol before output it in textarea:

if(str_startswith("\r\n",$value))
{
    $value = "\r\n".$value;             
}elseif(str_startswith("\n",$value))
{
    $value = "\n".$value;
}elseif(str_startswith("\r",$value))
{
    $value = "\r".$value;
}

function str_startswith($start, $string)
{
  if(mb_strlen($start)>mb_strlen($string))
    return FALSE;
  return (mb_substr($string, 0,mb_strlen($start))==$start);
}

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论