Forum Moderators: open

Message Too Old, No Replies

Counting characters in a textarea

Firefox vs IE

         

tata668

4:42 pm on Aug 31, 2005 (gmt 0)

10+ Year Member



I need to validate the number of characters in a textarea, using javascript.

I do something like:


if(document.myForm.myTextarea.value.length > 300)
{
alert("Max: 300 characters");
}

But Firefox sees newlines as 1 character while IE sees them as 2 characters!

Example, my textarea:
---------------
0123456789
0123456789
---------------

Firefox thinks there are 21 characters.
IE thinks there are 22 characters.

How can I count correctly for any browser?

Bernard Marx

9:24 pm on Aug 31, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I believe this is because a new line is \r\n in IE, but just \n in FF.

Normalise by removing any \rs in the value string before counting:

document.myForm.myTextarea.value.replace(/\r/g,'').length > 300

tata668

9:41 pm on Aug 31, 2005 (gmt 0)

10+ Year Member



Thanks! It works really well!

dcrombie

10:11 am on Sep 1, 2005 (gmt 0)



Not for Mac users - they only use '\r' and not '\n'...

Bernard Marx

11:32 pm on Sep 1, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Ah yes. Then we could just replace all possibles with any char - since the actual string is just being measured, not used.

document.myForm.myTextarea.value.replace(/\r¦\r\n¦\n/g,'x').length > 300

? ..and I'm not sure whether this will help at the server end.

tata668

4:01 pm on Sep 3, 2005 (gmt 0)

10+ Year Member



For a reason I don't understand "/\rŠ\r\nŠ\n/g" doesn't always work on IE...

But anyway, I think this will do the job:

document.myForm.myTextarea.value.replace(/\r\n/g,'x').length > 300

"\r" (ex: on mac) counts for one char, "\n" (ex: on Firefox) counts for one char and with this little script, "\r\n" (ex: on IE) also counts for one char.

Thanks again for your help!