This is an offshoot of this question: Chrome counts characters wrong in textarea with maxlength attribute
In that question it was found that Javascript counts carriage returns are one character when in fact it is two (\r\n
), why is that?
Test Fiddle: http://jsfiddle.net/maniator/E527z/
In that question it was found that Javascript counts carriage returns are one character when in fact it is two ( \r\n ), why is that? Here's your answer with evidence: whatwg.org/specs/web-apps/current-work/multipage/…
These are two characters: \r is carriage return; \n is line feed.
CR = Carriage Return ( \r , 0x0D in hexadecimal, 13 in decimal) — moves the cursor to the beginning of the line without advancing to the next line.
Yes, each line break, space and carriage return adds to your character count.
For reasons unknown, jQuery always converts all newlines in the value of a <textarea>
to a single character. That is, if the browser gives it \r\n
for a newline, jQuery makes sure it's just \n
in the return value of .val()
. (Actually the reason probably isn't "unknown"; it's probably to normalize the results across browsers, because IE reports newlines as being 2 characters long.)
Chrome and Firefox both count the length of <textarea>
tags the same way for the purposes of "maxlength".
However, the HTTP spec insists that newlines be represented as \r\n
. Thus, jQuery, webkit, and Firefox all get this wrong. When the field is posted, webkit and Firefox correctly add the newlines!
The upshot is that "maxlength" on <textarea>
tags is pretty much useless if your server-side code really has a fixed maximum size for a field value.
Edit This is still an issue in 2015 - at least on Chrome 45.0.2454 and IE 11.0.9600.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With