During my recent project and some before that I was in need to show the number of characters entered in a textbox to user so that she may know that the message (SMS or something) is touching the boundaries. Here in this post I will be discussing about showing a character count with max limit of 160, the counter shows in green until 140 is reached, turns orange when 140 exceeds and red when 160. You may find many examples over the internet about character count but I will also discuss the scenario when you edit the record and specially when you have 2 textboxes doing the same thing ie showing character count. Lets start with the javascript code called on: onKeyUp, onKeyDown and onChange events. In demo attached this function is present in script.js file
function textCounter(field, cntfield, maxlimit)
{
field = document.getElementById(field);cntfield = document.getElementById(cntfield); // imp otherwise throws error in IE on focusOut from textbox
//cntfield.width = “330px”;
cntfield.value = maxlimit + field.value.length;if (cntfield.value <= 140)
{
cntfield.className = “greenClass”;
cntfield.value = cntfield.value + ” characters are entered”;
}
else if (cntfield.value >= 140 && cntfield.value < 160)
{
cntfield.className = “yellowClass”;
cntfield.value = cntfield.value + ” characters are entered, You are nearing 160 characters limit”
}
else if (cntfield.value == 160)
{
cntfield.className = “redClass”;
cntfield.value = cntfield.value + ” characters limit is reached”;
}
}
In function textcounter 3 CSS classes are used that are present in style.css file in demo project attached. The asp.net textbox code is like that with the counter input showing the character count:
<asp:TextBox ID=”TextBox1″ runat=”server” CssClass=”txtbox”
MaxLength=”160″
onKeyDown=”textCounter(this.id,’remLen1′,0);”
onKeyUp=”textCounter(this.id,’remLen1′,0);”
onChange=”textCounter(this.id,’remLen1′,0);”></asp:TextBox> <input readonly=”readonly” type=”text” id=”remLen1″
style=”border-style:none; border-color:inherit; border-width:medium; width:380px;”
name=”remLen1″ value=”0 characters are entered” />
The given code will work fine when inserting or just a single functionality on edit time though we need to set the textbox value and also update the character count like this:
TextBox1.Text = “edit text”;
ClientScript.RegisterStartupScript(typeof(Page), “txt1″, string.Format(“textCounter(‘{0}’,'remLen1′,0);“, TextBox1.ClientID), true);
The orange text calls the javascript function described earlier and the ; at the end is the key to call the same line for TextBox2. If not present the call will not occur because the script is not terminated if “;” is not given.
In the attached demo there is an Edit button to demonstrate the Edit scenario, please Download and let me know if you find any difficulties or error in implementing this.




