Text Box Characters Counter (IE, Opera, FireFox, & Safari)

In forms when using text boxes or text areas with limited character length (usually needed for forms that submit data to a database) it is always a good idea to tell the user how many characters they have remaining. This javascript snippet is especially useful for textarea fields since they can't be assigned a text limit in HTML but can be restricted using this code.

The following example shows how you can do this. This is a very simple and cute idea to help the user know exactly how many characters can be typed further. Do these small add-ons to your forms and they will look really professional. We recommend using this counter inside CMS solutions and custom built Admin Panels where your clients/visitors can be instructed to use all browsers like IE, Opera, FireFox, Netscape or Safari.



JavaScript to be pasted in head tags

<script language = "Javascript">
/**
* DHTML textbox character counter script. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
*/

maxL=255;
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>

html code to be pasted within body tags


<font> Maximum Number of characters for this text box is 255.<br>
<textarea onKeyPress="return taLimit(this)" onKeyUp="return taCount(this,'myCounter')" name="Description" rows=7 wrap="physical" cols=40>
</textarea>
<br><br>
You have <B><SPAN id=myCounter>255</SPAN></B> characters remaining
for your description...</font>

0 comments:

Post a Comment