Saturday, September 23, 2006

Problems counting characters with JavaScript and Firefox?

Basically Firefox, when counting a textarea string length, counts each breakline as one characters, but expands it to CRLF when submitting. If you have a database limit and relies on JavaScript to keep your textarea under this limit, a simple JavaScript function will not work. Surprising, but it will work perfectly in Internet Explorer, although commonly the inverse is true when we find JavaScript problems.

To solve that problem, I created a modified version that seems to be working so far:

function textCounter(field,cntfield,maxlimit) {
var extra = 0;
if (navigator.appName=="Netscape" &&
parseInt(navigator.appVersion)>=5) {
var index = field.value.indexOf('\n');
while(index != -1) {
extra += 1;
index = field.value.indexOf('\n',index+1);
}
}
if (field.value.length + extra > maxlimit)
field.value = field.value.substring(0, maxlimit-extra);
else
cntfield.value = maxlimit - field.value.length - extra;
}


In case of Firefox (and Netscape, for that matter), it counts the breaklines, adding or subtracting this amount when checking the number of characters.

If you find some problem here or know a better version available on the internet, please let me know. I searched, but couldn't find a version that overcomes this Firefox behavior.
Post a Comment