Neal Neal - 2 years ago 68
Javascript Question

Why does Javascript only count carriage returns as one character when it is two?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download