Count Characters in a Text Area

 

Scenario : Suppose we have a function to send a mail.The mail will send only if the text count we have entered is less than 100.Else we have to show a javascript alert that says 'NO'. The count show not include the new line,space,carriage return etc.Only characters.Here i have given the code to do so.The whole functionality is written in client script.If you are stuck up with some thing pls mail me @ bonny_bros@yahoo.com

<HTML>

<div id="divContent">
<iframe width="440px" id="idContent" height="150px" runat="server"></iframe>
<input type="hidden" id="hdnidContent" runat="server" />
</div>

</HTML>

<script language="javascript">

// Function to get the values from text area( here it is < iframe /> ; dont be scared , get going) to a hidden field.This is for later computation.

function Getvalue()
{
document.getElementById('hdnidContent').value="";
document.getElementById('hdnidContent').value=document.getElementById('idContent').
contentWindow.document.body.innerHTML;
}

// Functions to Trim.Javascript has no built in trim mechanism.This is a user defined function

function LTrim( value )
{
var re = /\s*((\S+\s*)*)/;
return value.replace(re, "$1");
}
function RTrim( value )
{
var re = /((\s*\S+)*)\s*/;
return value.replace(re, "$1");
}
function trim( value )
{
return LTrim(RTrim(value));
}

// Function to replace the new line,carriage return,white spaces as null

function HTMLDecode(encodedstring)
{
var reg=/&nbsp;/g;
encodedstring = encodedstring.replace(reg,'');
reg=/<br>/g;
encodedstring = encodedstring.replace(reg,'');
reg=/<P>/g;
encodedstring = encodedstring.replace(reg,'');
reg=/<\/P>/g;
encodedstring = encodedstring.replace(reg,'');
return encodedstring;
}

// Function to validate the textarea

function fnValidate()
{
Getvalue();
var strWhite=new Array();
framecont=HTMLDecode(document.getElementById('hdnidContent').value);
framecont=trim(framecont);
framecont=framecont.replace(/\r|\n|\r\n/g,"");
strWhite=framecont.split(" ");
var totalSize=0;
for(var i=0;i<strWhite.length;i++)
{
totalSize=totalSize + strWhite[i].length;
}
if(totalSize >100)
{
alert("Enter content less than 100 ");
document.getElementById("idContent").contentWindow.focus();
return false;
}
}

// Calling in the function.In your application you can write according to your need.
fnValidate();

</script>