Characters Count in a Text Box

Lakhangarg
Posted by Lakhangarg under JavaScript category on | Views : 4166
This java code sample shows how to find the Characters Count in a Text Box.
Call to JavaScript Method on Different Event (onkeypress,onkeyup,onkeydown,onPaste) of TextBox
private void AddScriptCounter()
{
txtMessage.Attributes.Add("onkeypress", "CountCharactersGeneral('" + txtMessage.ClientID +

"','inputTxtMessageCountAge'," + 4000 + ")");
txtMessage.Attributes.Add("onkeyup", "CountCharactersGeneral('" + txtMessage.ClientID +
"','inputTxtMessageCountAge'," + 4000 + ")");
txtMessage.Attributes.Add("onkeydown", "CountCharactersGeneral('" + txtMessage.ClientID +
"','inputTxtMessageCountAge'," + 4000 + ")");
txtMessage.Attributes.Add("onPaste", "CountCharactersGeneral('" + txtMessage.ClientID +
"','inputTxtMessageCountAge'," + 4000 + ")");
}


Java Script Code
Javascript Method to COunt the Character and Restrict to the maximum charcter that can be entered into a textbox.
sourceTextBox (Source Text Box)
displayControl (Control where you want to diplay remaing characters count)
maxLength (Maximum number of Character that can be entered into the Source Text Box.)
function CountCharactersGeneral(sourceTextBox, displayControl, maxLength)
{

if(sourceTextBox != null && displayControl != null)
{
sourceTextBox = document.getElementById(sourceTextBox);
displayControl = document.getElementById(displayControl);
if(sourceTextBox != null)
{
var len = sourceTextBox.value.length
if (len<=maxLength) //if entered charcters less than the Maximum Limit.
{
//Shows Number of characters Remaining
displayControl.innerHTML = maxLength -len + " Character(s) remaining.";
}
else
{
sourceTextBox.value = sourceTextBox.value.substring(0, maxLength);
return false;
}
}
}
}


Thanks & Regards
Lakhan Pal Garg

Comments or Responses

Login to post response