'JavaScript validation function on Firefox

I have the following code which works perfect in IE for a textarea element.

<textarea name="mem_message" cols="25" rows="5"
  onkeypress="return taLimit(this)" 
  onkeyup="return taCount(this,'myCounter')">
    <? echo $_SESSION['mem_message']; ?>
</textarea>

It calls a validation function:

<script language="Javascript"><!--Counter for Message Box -->

maxL=100;
var bName = navigator.appName;
function taLimit(taObj) {
    if (taObj.value.length==maxL) return false;
    return true;
}

function taCount(taObj,Cnt) { 
    objCnt=createObject(Cnt);
    objVal=taObj.value;
    if (objVal.length>maxL) objVal=objVal.substring(0,maxL);
    if (objCnt) {
        if(bName == "Netscape"){    
            objCnt.textContent=maxL-objVal.length;}
        else{objCnt.innerText=maxL-objVal.length;}
    }
    return true;
}
function createObject(objId) {
    if (document.getElementById) return document.getElementById(objId);
    else if (document.layers) return eval("document." + objId);
    else if (document.all) return eval("document.all." + objId);
    else return eval("document." + objId);
}
</script>

All the above works on IE only. On Firefox it won't even focus on the box.



Solution 1:[1]

Few pointers:

  • Don't use language="javascript", it's deprecated.
  • Don't use eval for property access, it's slow and unnecessary.
  • Don't sniff for "Netscape", instead check property/method existence/compliance (innerText/textContent)
  • Don't name a method for receiving an element as "createObject", it's misleading.
  • Don't perform undeclared assignment (maxL = 100), it's error prone.
  • Don't capitalize variable names that are not constructors (or namespaces), for convention.
  • Try not to declare functions in global scope, to avoid name conflicts.

Solution 2:[2]

Here's a better script to count characters in a textarea: http://sliceofcake.wordpress.com/2007/08/16/count-characters-in-a-textarea/

Hope it's what you're looking for!

Solution 3:[3]

The attributes for event handlers are meant to be in all lower case; have you tried onkeyup rather than onKeyUp, etc.?

Solution 4:[4]

Please read Unobtrusive JavaScript here http://en.wikipedia.org/wiki/Unobtrusive_JavaScript before doing any development in JavaScript.

You will thank me many times over later!

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 kangax
Solution 2 Emil Stenström
Solution 3 T.J. Crowder
Solution 4 OpenSource