ASP.NET Text Character Counter

A textbox character counter is a pretty simple piece of functionality, and there's a lot of different ways to apply one to your application. The following method is nice and simple, and can be done using only clientside JavaScript if required, or combined with server side code in order to create a more dynamic effect (ie, turning the counter on/off conditionally).

First, we'll add the most basic static implementation of the field counter to a form using only a JavaScript function and event handlers in the aspx file, then we'll look at how we can extend the functionality and dynamic nature of the counter by using server side code.

Basic Implementation
First, we need to add a small JavaScript function somewhere. For now, just add it somewhere in your form body, or if you have a common library of JavaScript functions in a .js file, simply add it in there. The function looks like this: <script type="text/javascript">

function textCounter(field, countfield, maxlimit)
{
if (field.value.length > maxlimit)
   field.value = field.value.substring(0, maxlimit);
else
   countfield.value = maxlimit - field.value.length;
}

</script>

Now add the event handlers to the text field, which in this case is called 'txtMessage':
<asp:TextBox ID="txtMessage" TextMode="MultiLine"  Width="200px" Rows="3" runat="server"  onkeyup="textCounter(txtMessage, this.form.remLen, 160);" onkeydown="textCounter(txtMessage, this.form.remLen, 160);" />

Finally, add the HTML input field which will display the counter:
<input readonly="readonly" type="text" name="remLen" size="3" maxlength="3" value="160" /> characters left

That's the basic implementation done. Pretty simple.

You should now be able to load your form, and type text in the textbox while the counter updates. Once you hit your character limit, you'll be prevented from typing any more characters in the box.

This all works fine in a simple example, but there are some serious limitations with the static implementation. What happens if txtMessage is embedded inside another element, such as a DataGrid or Repeater? It's name will no longer simply be 'txtMessage', as the name of the parent control will be added when it's rendered to the browser. What happens if we want to remove the character counter for any reason based on the contents of the page? Finally, what about if we want to change the way our JavaScript function performs for any reason? These are all limitations we can overcome with serverside code.

Adding some Server Side smarts
First, lets revisit the JavaScript function. Maybe for some reason we don't want to add it to a .js library, or to the .aspx file, then as an alternative we can dynamically add the function in either the Page_Load or the OnLoad event of our page using Page.ClientScript.RegisterClientScriptBlock (if you're using ASP.NET 1.1 then this is Page.RegisterClientScriptBlock), like so:
protected void Page_Load(object sender, EventArgs e)
{
    string theFunction = @"<script language=javascript>
function textCounter(field, countfield, maxlimit)
{
                if (field.value.length > maxlimit)
                    field.value = field.value.substring(0, maxlimit);
                else
                    countfield.value = maxlimit - field.value.length;
                }
            </script>";

    Page.ClientScript.RegisterClientScriptBlock(this.GetType(),
        "ClientScriptFunction", theFunction);
}

In this simple example it doesn't seem overly useful, however consider the fact that you could dynamically change the way the JavaScript behaves here in the code (possibly based on the state of the page), and dynamically output a different function based on different scenarios. Using String.Format you can cleanly manipulate this function, and substitute parts of it at will - for example, if your JavaScript function contained text messages that were displayed to the user, then this would be an easy place to add multi language support.

Now, lets change the event handlers on the txtMessage field so they're created dynamically when the page loads. Remove the onkeyup and onkeydown events from your definition of txtMessage in the aspx file, and add the following code to your Page_Load or OnLoad event in code:
string theFunction = "javascript:textCounter(" + txtMessage.ClientID + ",this.form.remLen,160);";

txtMessage.Attributes.Add("onKeyDown", theFunction );
txtMessage.Attributes.Add("onKeyUp", theFunction);

This solves a couple of issues for us. Firstly, we no longer need to worry about what the exact name of our textbox control 'txtMessage' ends up being. It can be nested inside repeaters, grids, whatever - txtMessage.ClientID will always return the full and proper name for us. This also means we can apply counters across multiple textboxes on a form, however we'd obviously need to add multiple output fields to our form somewhere and modify the JavaScript function accordingly. We also have the ability to change which control we want to apply the counter to - if we need to select which textbox is having the counter applied to it when the form loads, then we can do that simply by using it's ClientID property. Adding the events in code also allows us to easily disable the counter if we need to. For example, consider that txtMessage resides on a form which is used to send a message via SMS or Email. The 160 character limitation isn't required for email, so if that's what the user has selected, then we can simply not add the event handlers to the txtMessage control when the page is (re)loaded. in this case, you might want to enclose the html output field and text in a panel, and show/hide that accordingly as well as shown in the following simple example:
 if(rbModeSelect.SelectedValue == MessageTypesEnum.SMS.ToString())
 {
  string theFunction = "javascript:textCounter(" + txtMessage.ClientID + ",this.form.remLen,160);";

  txtMessage.Attributes.Add("onKeyDown", theFunction);
  txtMessage.Attributes.Add("onKeyUp", theFunction);
  pnlSMSCharsRemaining.Visible = true;
}
else
{
  txtMessage.Attributes.Remove("onKeyDown");
  txtMessage.Attributes.Remove("onKeyUp");
  pnlSMSCharsRemaining.Visible = false;
}

Tags:

Summary
The above example shows you how to implement a pretty simple character counter to a text field. However it should also give you an insight into some of the functionality that is available when you combine client side script with server side code. I'll discuss this further in one of my next articles, expanding on these concepts as well as showing a few more advanced techniques.

EDIT: 07 Feb 09, For those of you who are trying to get something like this to work with Master Pages, I've created a quick update post: ASP.NET Text Character Counter – the Master page version

Posted on Monday, December 4, 2006 10:35 PM | ASP.NET Web Development C#

Like this? Share it!

  • # ASP.NET Text Character Counter
    Gravatar
    Commented on 3/16/2007 10:30 PM

    it is good

  • # ASP.NET Text Character Counter
    Gravatar
    Commented on 3/26/2007 9:25 PM

    does the job nicely - ta!

  • # ASP.NET Text Character Counter
    Gravatar
    Commented on 8/1/2007 7:42 AM

    How do you make this work inside of a masterpage?

  • # ASP.NET Text Character Counter
    Gravatar
    Commented on 8/1/2007 10:46 PM

    I can't see anything there which would have a problem inside a master page. What sort of problems are you experiencing?

  • # ASP.NET Text Character Counter
    Gravatar
    Commented on 8/2/2007 1:38 AM

    My code appears to be generating correctly. I am dynamically naming both my textarea and my label control. (I was having an issue with the generated javascript when I tried naming my label control, so I let the server do it).

    Both my textarea and label are runat=server.

    When I type inside my textbox I get no javascript errors BUT my label does not change.

  • # ASP.NET Text Character Counter
    Gravatar
    Commented on 8/2/2007 7:56 PM

    Hi James, I've replied to your email - let me know how you get on!

  • # re: ASP.NET Text Character Counter
    Gravatar
    Commented on 9/21/2007 6:22 PM

    Thanks for that!

    After a bit of modification I got it to work inside a DetailsView using something like this:

    TextBox txtTestDesc = (TextBox)dvwGeneral.FindControl("TestDescription");

    if (txtTestDesc != null)
    {
    string theFunction = "javascript:textCounter(" + txtTestDesc.ClientID + ",this.form.remDescLen,255);";

    txtTestDesc.Attributes.Add("onKeyDown", theFunction);
    txtTestDesc.Attributes.Add("onKeyUp", theFunction);
    }

  • # re: ASP.NET Text Character Counter
    Gravatar
    Commented on 10/30/2007 8:01 AM

    I have four text boxes. There are four separate text boxes because there needs to be reporting on the data placed in those text boxes. the data from the four text boxes need to combined in a single string to be displayed on a web page in a limited space (255 char total). How can I use this functionality to combine the character count to span all four text boxes?

  • # re: ASP.NET Text Character Counter
    Gravatar
    Commented on 12/14/2007 8:46 PM

    erfefefe

  • # re: ASP.NET Text Character Counter
    Gravatar
    Commented on 2/15/2008 8:38 AM

    Just what i needed, thx!

  • # re: ASP.NET Text Character Counter
    Gravatar
    Commented on 5/31/2008 5:14 PM

    How do you make this work inside of a masterpage?

  • # re: ASP.NET Text Character Counter
    Gravatar
    Commented on 8/1/2008 6:18 AM

    Nice work, thank you :)

  • # re: ASP.NET Text Character Counter
    Gravatar
    Commented on 8/20/2008 9:49 PM

    Really thanks for it !!! it really help a lot! :)

  • # re: ASP.NET Text Character Counter
    Gravatar
    Commented on 9/18/2008 9:20 PM

    hi, could this work in a gridview to show character counts against each comments box running down the column?
    ie

    row1:textbox1: comments : this is a test 14 char
    row2:textbox2: comments : this is also a test 19 chars

    etc ?

  • # re: ASP.NET Text Character Counter
    Gravatar
    Commented on 9/19/2008 9:31 AM

    Hi Dave,

    It'd need some modification to work inside a gridview, but the basic concept still applies. I'm not sure whether you're going to be modifying your gridview to always be in edit mode, or if you're going to use some sort of a bulk edit mode, or whether you're talking about showing character counts against non editable comments? If you're talking about the last option there's easier ways to do it.

    Give me some more info and I'll see if I can be of more assistance!

  • # re: ASP.NET Text Character Counter
    Gravatar
    Commented on 10/9/2008 6:20 PM

    How would i go with ASP.NET 2.0 as there are no onKeyUp and OnKeyDown associated with Textbox Control.

  • # re: ASP.NET Text Character Counter
    Gravatar
    Commented on 10/9/2008 9:36 PM

    Hi Atish,

    I was using ASP.NET 2.0 in my example - even though there's no intellisense and the IDE claims that event doesn't exist, it does. So just ignore the warnings and you should be fine.

  • # re: ASP.NET Text Character Counter
    Gravatar
    Commented on 10/17/2008 12:24 PM

    hi.
    thanks. but why it doesn't work?
    the TextBox doesn't have onkeyup or onkeydown eventhandlers, should i add them?
    is the first code(simple) complete?

  • # re: ASP.NET Text Character Counter
    Gravatar
    Commented on 10/17/2008 1:46 PM

    the <textarea> have these attributes but TextBox!
    the second problem is typing wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww from users. how can i breck it so it doesn't destroy my website appearance?

    thank you

  • # re: ASP.NET Text Character Counter
    Gravatar
    Commented on 10/21/2008 9:30 AM

    Hi Ashkan,

    The first code sample is complete. The onkeyup and onkeydown events clientside events of the rendered input tag, not of the asp:Textbox. So the IDE complains that they don't exist, but when the page is rendered the client knows what to do.

  • # re: ASP.NET Text Character Counter
    Gravatar
    Commented on 11/25/2008 6:43 PM

    Thanx Alot


    nice code

  • # re: ASP.NET Text Character Counter
    Gravatar
    Commented on 12/2/2008 2:43 PM

    nice code. it really helps alot. thanks.

  • # re: ASP.NET Text Character Counter
    Gravatar
    Commented on 12/2/2008 2:43 PM

    nice code. it really helps alot. thanks.

  • # re: ASP.NET Text Character Counter
    Gravatar
    Commented on 12/9/2008 11:36 PM

    nothing works.. in .Net 1.1

  • # re: ASP.NET Text Character Counter
    Gravatar
    Commented on 12/9/2008 11:40 PM

    OOps... sry for the previous comment.. i forgot to change the ID of my text box.. it works great.. thnx a lot.

  • # re: ASP.NET Text Character Counter
    Gravatar
    Commented on 1/7/2009 7:37 PM

    Hi,

    Works like a charm.

    Thanks.

  • # re: ASP.NET Text Character Counter
    Gravatar
    Commented on 1/31/2009 4:48 AM

    Cant get the count to work on my aspx page!!

  • # re: ASP.NET Text Character Counter
    Gravatar
    Commented on 1/31/2009 8:45 AM

    Hi Michael,

    You might need to elaborate on that a little..

  • # re: ASP.NET Text Character Counter
    Gravatar
    Commented on 2/6/2009 5:22 AM

    I could not get this to work either. My aspx page is contained in a Masterpage.

    Here is the following code from the Page_Load event

    Dim theFunction As String = "<script type='text/javascript'> function textCounter(field, countfield, maxlimit){If (field.value.length > maxlimit) {field.value = field.value.substring(0, maxlimit);} else {countfield.value = maxlimit - field.value.length;} }</script>"
    Page.ClientScript.RegisterClientScriptBlock(Me.GetType(), "ClientScriptFunction", theFunction)

    theFunction = "javascript:textCounter(" & txtAddUserComment.ClientID & "," & lblUserCharCount.ClientID & ",200);"

    txtAddUserComment.Attributes.Add("onKeyDown", theFunction)
    txtAddUserComment.Attributes.Add("onKeyUp", theFunction)

    theFunction = "javascript:textCounter(" & txtAddAdminComments.ClientID & "," & lblAdminCharCount.ClientID & ",200);"
    txtAddAdminComments.Attributes.Add("onKeyUp", theFunction)
    txtAddAdminComments.Attributes.Add("onKeyDown", theFunction)

    I get an Object Expected JS error in my browser.

  • # re: ASP.NET Text Character Counter
    Gravatar
    Commented on 2/7/2009 10:51 AM

    Can't get it to work in a masterpage either... anyone have any luck?

  • # re: ASP.NET Text Character Counter
    Gravatar
    Commented on 2/7/2009 6:08 PM

    Hi all,

    I've posted a quick update to the article including a couple of examples of counters which are compatiable with Master Pages:

    www.rosshawkins.net/archive/2009/02/07/577.aspx

    Please let me know if you're still having problems!

  • # re: ASP.NET Text Character Counter
    Gravatar
    Commented on 2/8/2009 6:26 AM

    Thanks, I really appreciate it, I will look into that on Monday.

  • # re: ASP.NET Text Character Counter
    Gravatar
    Commented on 2/10/2009 9:10 PM

    That is spot on. I can testify that this works with masterpages. Cheers Ross.

  • # re: ASP.NET Text Character Counter
    Gravatar
    Commented on 2/13/2009 10:37 PM

    Ross

    I have the text counter appearing on my aspx page and it contains the 160 characters but when I type into the textbox the 160 does not change? My code is as follows:

    .js File


    function textCounter(field, countfield, maxlimit)
    {
    if (field.value.length > maxlimit)
    field.value = field.value.substring(0, maxlimit);
    else
    countfield.value = maxlimit - field.value.length;
    }


    apsx page

    <asp:TextBox ID="txt_Q6" runat="server" Rows="5" CssClass="survey_textbox" TextMode="MultiLine" onkeyup="textCounter(txtMessage, this.form.remLen, 160);" onkeydown="textCounter(txtMessage, this.form.remLen, 160);">
    </asp:TextBox>


    <input readonly="readonly" type="text" name="remLen" size="3" maxlength="3" value="160" /> characters left

    Does this make it any clearer?

    Mick

  • # re: ASP.NET Text Character Counter
    Gravatar
    Commented on 2/13/2009 11:09 PM

    Michael,

    The first argument to the onkeyup function needs to be the id of your text box - in your case, you need to pass txt_Q6 instead of txtMessage.

    If you've got more than one of those fields you might want to look at adding the counter dynamically in codebehind.

  • # re: ASP.NET Text Character Counter
    Gravatar
    Commented on 2/13/2009 11:38 PM

    Ross

    I just realised that when I posted the last comment and changed it but it still did not work!!

    The <script type="text/javascript"> at the top of the .js file is not reconised if that has any bearing on it.

    Any other suggestions Ross?

    Mick

  • # re: ASP.NET Text Character Counter
    Gravatar
    Commented on 3/1/2009 6:07 PM

    i still cant get the code working....

  • # re: ASP.NET Text Character Counter
    Gravatar
    Commented on 3/2/2009 9:54 PM

    Prashant,

    Can you either post a bit more info here or email me? A bit more background about what you're trying to do and any error messages you're seeing would be useful.

    Also, if you're using Master Pages then be sure to check out this link: www.rosshawkins.net/archive/2009/02/07/577.aspx

  • # re: ASP.NET Text Character Counter
    Gravatar
    Commented on 4/11/2009 4:56 AM

    I copied, I pasted, it worked! Thanks for saving me a lot of time! I just wish my Google search would have been smarter from the start so I would have hit this link first.

    I added an inline style to the <input> tag: style="border: solid 0px white; background: white;"

    I wanted the <input> to look like text in a <span> rather than text in a text box. This did the trick. Note, change both instances of "white" to whatever the background of the page is.

    And yes, 0px white is overkill. Either will effectively make the border invisible.

  • # re: ASP.NET Text Character Counter
    Gravatar
    Commented on 5/25/2009 1:45 AM

    Great code thanks a bunch

  • # re: ASP.NET Text Character Counter
    Gravatar
    Commented on 7/3/2009 3:23 AM

    Thank you .

  • # re: ASP.NET Text Character Counter
    Gravatar
    Commented on 7/11/2009 12:49 PM

    Thank you.

  • # re: ASP.NET Text Character Counter
    Gravatar
    Commented on 7/11/2009 12:51 PM

    Thank you admin

  • # re: ASP.NET Text Character Counter
    Gravatar
    Commented on 7/11/2009 12:55 PM

    Thank you veryy very nice

  • # re: ASP.NET Text Character Counter
    Gravatar
    Commented on 7/11/2009 12:57 PM

    Thank you very much

  • # re: ASP.NET Text Character Counter
    Gravatar
    Commented on 7/14/2009 8:40 PM

    Wait, actually, that wouldn't work. The aforementioned if() statement takes code and chops it off using substring(). And textareas don't have a length attribute that I know of.

  • # re: ASP.NET Text Character Counter
    Gravatar
    Commented on 7/18/2009 9:21 AM

    I am grateful to you for this great content.

  • # re: ASP.NET Text Character Counter
    Gravatar
    Commented on 9/13/2009 8:37 AM

    i'm beginner thanks ffpost

  • # re: ASP.NET Text Character Counter
    Gravatar
    Commented on 9/13/2009 8:38 AM

    Thanks for post nice to use asp.net

  • # re: ASP.NET Text Character Counter
    Gravatar
    Commented on 10/10/2009 12:57 AM

    thanks

  • # re: ASP.NET Text Character Counter
    Gravatar
    Commented on 10/11/2009 8:15 AM

    very usefull thank you

  • # re: ASP.NET Text Character Counter
    Gravatar
    Commented on 12/26/2009 7:02 PM

    Visual Studio 2005 already does everything. I’m working on an ASP.NET 3.5 web site using Visual Studio 2005 until I get Visual Studio 2008. there are some pretty significant language changes in both VB and C# as well as some pretty nice IDE changes, that you just won’t be able to use until or unless you move to 2008.i found this informative and interesting blog so i think so its very useful and knowledge able.so it is great usability and good for us.I would like to thank you for the efforts you have made in writing this article.

  • # re: ASP.NET Text Character Counter
    Gravatar
    Commented on 1/28/2010 9:56 AM

    this is a great article

  • # re: ASP.NET Text Character Counter
    Gravatar
    Commented on 2/25/2010 5:45 AM

    I like the 8:00 weekday starts much better than the 7:00. I think you'll see attendance number rise a bit for these weekday games.

  • # re: ASP.NET Text Character Counter
    Gravatar
    Commented on 3/16/2010 6:47 PM

    Is there anything special I would need to do to use the first simple example on more than one textbox? Sorry if that's a dumb question...kind of new to asp

  • # re: ASP.NET Text Character Counter
    Gravatar
    Commented on 4/10/2010 10:10 PM

    I don't believe that event.srcElement exists in Firefox. In Firefox I believe that it is event.target. Try
    var tbObj = (typeof event.target != 'undefined') ? event.target : event.srcElement;

  • # re: ASP.NET Text Character Counter
    Gravatar
    Commented on 5/10/2010 7:56 AM

    great article thanks

  • # re: ASP.NET Text Character Counter
    Gravatar
    Commented on 5/27/2010 5:55 AM

    thank you so much - my website was almost complete apart from this missing function and i couldnt work out a way to code it then i found your site...

    thanks for sharing, it's really appreciated...

    p.s. for anyone else doing this visual web will produce errors in the code with onkeyup and onkeydown but it runs fine anyway

  • # re: ASP.NET Text Character Counter
    Gravatar
    Commented on 5/27/2010 6:07 AM

    great... thanks

    just one question: is there a way i can get round the problem if the user uses copy and paste...???


  • # re: ASP.NET Text Character Counter
    Gravatar
    Commented on 5/27/2010 7:48 AM

    If you set the MaxLength property on the textbox then it won't accept anything above this limit. Or alternatively, you could (and should) be performing additional validation server side (or in Javascript) to truncate text to provide a better user experience.

  • # re: ASP.NET Text Character Counter
    Gravatar
    Commented on 6/15/2010 8:49 AM

    Yeah.. Its very useful coding for beginers also me...

    Regards,

    D.Veeramanikandan

  • # re: ASP.NET Text Character Counter
    Gravatar
    Commented on 8/20/2010 11:34 AM

    Thanx Alot

  • # thnx for post very nice informations
    Gravatar
    Commented on 8/28/2010 1:41 AM

    thnx for post very nice informations

  • # re: ASP.NET Text Character Counter
    Gravatar
    Commented on 6/28/2011 4:59 PM

    Really Nice post.Great help.Thnx

  • # re: ASP.NET Text Character Counter
    Gravatar
    Commented on 11/24/2011 3:30 AM

    This post was EXTREMELY helpful. I am normally a PHP/MySQL Developer but recently had to do some work on a .NET project, this helped me learn some of the anomalies.

    Thanks!!!

  • # re: ASP.NET Text Character Counter
    Gravatar
    Commented on 1/6/2012 4:50 AM

    Great article, I needed a similar control and I came across this one here jasear.wordpress.com/.../net-webcontrol-textbox... which worked like a charm, I think it uses a similar approach to yours.

  • # re: ASP.NET Text Character Counter
    Gravatar
    Commented on 12/27/2012 10:22 AM

    I want to make this as a User control. AS i need this textarea more than in one my page.
    Any help would be greatly appreciated.

    Thanks
    Saritha.

Post a comment
Please add 5 and 8 and type the answer here:
Remember me?
Ensure the word in this box says 'orange':