Welcome to WebmasterWorld Guest from 34.204.203.142

Forum Moderators: open

Message Too Old, No Replies

Counting characters in a textarea

Firefox vs IE

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

Full Member

10+ Year Member

joined:Feb 9, 2005
posts:228
votes: 0


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?

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

Senior Member

WebmasterWorld Senior Member 10+ Year Member

joined:Apr 15, 2004
posts:2047
votes: 0


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
9:41 pm on Aug 31, 2005 (gmt 0)

Full Member

10+ Year Member

joined:Feb 9, 2005
posts:228
votes: 0


Thanks! It works really well!

dcrombie

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

Inactive Member
Account Expired

 
 


Not for Mac users - they only use '\r' and not '\n'...
11:32 pm on Sept 1, 2005 (gmt 0)

Senior Member

WebmasterWorld Senior Member 10+ Year Member

joined:Apr 15, 2004
posts:2047
votes: 0


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.

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

Full Member

10+ Year Member

joined:Feb 9, 2005
posts:228
votes: 0


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!