Wednesday, December 23, 2009

Javascript textfield counter

maxL = 1000;
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) {
alert("Description field has to be less than 1000 characters.");
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);
}


To update the counter at last, do something like this:
<script type="text/javascript">
taCount(document.getElementById('txtDescription'), 'myCounter');
</script>

No comments: