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

后端 未结 1 584
暗喜
暗喜 2020-12-28 19:19

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

相关标签:
1条回答
  • 2020-12-28 19:47

    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.

    0 讨论(0)
提交回复
热议问题