Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Internet Explorer: how to escape extra carriage return after editing Textarea?

We have a multiline textarea in Internet Explorer.

If we check it's content after the next then everything is correct (there are no extra carriage returns in textarea):

document.getElementById( 'text-area' ).value = "Hello,\nWorld!";

But if we set caret to the beginning position of the second line (in Internet Explorer, not in the code) and press tab key there is an extra carriage character (there is a string dump on keydown below):

value[0]='H'
value[1]='e'
value[2]='l'
value[3]='l'
value[4]='o'
value[5]=','
value[6]='\r'
value[7]='\n'
value[8]='W'
value[9]='o'
value[10]='r'
value[11]='l'
value[12]='d'
value[13]='!'

It's a problem because other browsers don't insert extra carriage return.

Do you know how to prevent this in Internet Explorer? With help of CSS or Javascript.

like image 666
sergzach Avatar asked Jun 20 '11 14:06

sergzach


1 Answers

You cannot prevent it, and you probably shouldn't anyway. Despite the fact that IE and other browsers differ in the way that they report the value of <textarea> elements, all browsers actually do include "\r\n" for all hard line breaks in the value when the form surrounding the element is submitted. In other words, even though Firefox reports line breaks as consisting of just "\n", it's actually lying to you — when the form is posted, the value will have "\r" in there too.

For some reason, jQuery normalizes the behavior across browsers by stripping out the "\r" characters, which of course is the wrong thing to do. It means that when you're trying to count characters (like the Stackoverflow comment box), you have to take into account the fact that each single "\n" character actually represents two characters at the server. Thus you have to either strip out the "\r" on the server, or, probably better, account for it in the client-side validation code.

like image 187
Pointy Avatar answered Oct 18 '22 09:10

Pointy