Codex73
Codex73

Reputation: 5766

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.

Upvotes: 1

Views: 604

Answers (4)

OpenSource
OpenSource

Reputation: 2257

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!

Upvotes: 0

Emil Stenstr&#246;m
Emil Stenstr&#246;m

Reputation: 14106

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!

Upvotes: 1

kangax
kangax

Reputation: 39188

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.

Upvotes: 10

T.J. Crowder
T.J. Crowder

Reputation: 1075289

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

Upvotes: 0

Related Questions