ASP.NET Text Character Counter – the Master page version

Back in December 2006 I wrote an article titled adding a quick character counter to a textbox in ASP.NET. Over 2 years later, and the article still gets a lot of views as well as a fair few comments – it seems there are a few people out there who needed character counters on their textboxes!

After getting a couple of recent comments from people who couldn't get it to work in a Master Page I thought I'd post a quick update to the article and include a couple of methods which work with Master Pages.

(Note: If I had to do something like this today, I'd use jQuery, which would be a lot simpler, however all I want to do here is to post a quick update to my original article. Also, please excuse the poor code formatting - I've not had a chance to setup a C# code formatter, although I know there are plenty of them out there).

The quick and simple version

First, the quick and simple version – lets get this working in a master page nice and quickly. Simply change the first parameter of your onkeyup and onkeydown events to be 'this', as shown below:

<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder" runat="server">
   
        <h4>Count This Text</h4>
       
        <asp:TextBox ID="txtToCount" TextMode="MultiLine"
                runat="server" onkeyup='textCounter(this, this.form.remLen, 160);'
                onkeydown="textCounter(this, this.form.remLen, 160);" /> 
        <br />
        <input readonly="readonly" type="text" name="remLen" size="3" maxlength="3" value="160" /> characters left
</asp:Content>

The JavaScript function for this example is the same as my previous post, but here it is again for completeness:

<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>

A quick note here – if you're using Visual Studio 2005, then it might complain that onkeyup and onkeydown aren't valid events for an asp:TextBox – don't worry about that, it's not Visual Studio which needs to know about those events, it's the browser, and in that context they're perfectly valid. They've fixed this issue in Visual Studio 2008, but from a few of the comments in the previous article there are still a lot of people out there using 2005.

Using a .NET control for the counter output

The above sample is very quick and basic – but it will only work with a html control for the display of the counter. If you need your output to go to an ASP.NET control, then we can hack things about to achieve that.

First, our content in the master page. It's the same as before, but I'm displaying the counter in an asp:TextBox, and as I'm no longer using a simple html input for the counter, I've replaced this.form.remLen with a variable called outputField.


<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder" runat="server">
   
        <h4>Count This Text</h4>
        <asp:TextBox ID="txtToCount" TextMode="MultiLine"
                runat="server" onkeyup='textCounter(this, outputField, 160);'
                onkeydown="textCounter(this, outputField, 160);" />
       
        <br />
        <asp:TextBox ID="txtOutput" Text="160" runat="server" />
</asp:Content>

Next I assign the outputField variable a value. I do this by grabbing the ClientID for my ASP.NET control, and storing in my variable. I've placed this in my head ContentPlaceHolder, but you can put it anywhere you like. When the page loads, the variable will look something like 'ctl00_ContentPlaceHolder_txtOutput'.

<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
    <script language="javascript" type="text/javascript">
        var outputField = '<%= txtOutput.ClientID %>';
    </script>
</asp:Content>

Finally, we need to modify our JavaScript function slightly. The previous version was sent through a reference to the actual control, whereas now all we're passing through is the ID of an element in the DOM. So we modify the JavaScript to use the ID and grab the reference to the control:

<script type="text/javascript">
    function textCounter(field, countfield, maxlimit) {
        var output = document.getElementById(countfield);
        if (output == null) {return;}
       
        if (field.value.length > maxlimit)
            field.value = field.value.substring(0, maxlimit);
        else
            output.value = maxlimit - field.value.length;
    }
</script>

And we're done. You may wonder why the need for the JavaScript variable? Why can't we simply use txtOutput.ClientID in the declaration of our onkeyup and onkeydown events like this:


<asp:TextBox ID="txtToCount" TextMode="MultiLine" runat="server" onkeyup='textCounter(this, "<%= txtOutput.ClientID %>", 160);' onkeydown='textCounter(this, "<%= txtOutput.ClientID %>", 160);' />

This is becasue the ASP.NET parser can not parse the tag "<% =  %>" for a server side control (i.e. any control with runat="server"), so the above control would be rendered in HTML as:


<textarea name="ctl00$ContentPlaceHolder$txtToCount" rows="2" cols="20" id="ctl00_ContentPlaceHolder_txtToCount" onkeyup="textCounter(this, &quot;&lt;%= txtOutput.ClientID %>&quot;, 160);" onkeydown="textCounter(this, &quot;&lt;%= txtOutput.ClientID %>&quot;, 160);"></textarea>

Which is obviously not going to work.

Summary

A couple of things to mention - I've only tested the above examples in Firefox 3 and IE 7. Also, if you're looking to do something like this, or anything with JavaScript then you should check out jQuery. It makes any JavaScript related work a LOT simpler, and is a lot cleaner than the methods I've posted above.

Hope this helps!

Link: ASP.NET Text Character Counter (Original article)

Posted on Saturday, February 7, 2009 5:53 PM |

Like this? Share it!

  • # re: ASP.NET Text Character Counter – the Master page version
    Gravatar
    Commented on 2/10/2009 10:12 AM

    Both of them worked wonderfully, just what I needed, appreciate it!

  • # re: ASP.NET Text Character Counter – the Master page version
    Gravatar
    Commented on 2/10/2009 9:11 PM

    Nice one Ross... does the job perfectly!

  • # re: ASP.NET Text Character Counter – the Master page version
    Gravatar
    Commented on 4/1/2009 3:23 AM

    Thank you so very much. It probably didn't take much of your time to write up this code but you have single handedly brought to a succesful end hours of one young programmer's quest to implement a simple character counter - makes me feel a bit silly after I found out how simple it was, actually. God bless you!

  • # re: ASP.NET Text Character Counter – the Master page version
    Gravatar
    Commented on 4/13/2009 11:02 AM

    This code is tight! Even in Dotnetnuke. I did have to put the textCounter javascript function in the default.aspx page though even when the place I was using it was in another web user control.

    Thank you for this nice solution.

  • # re: ASP.NET Text Character Counter – the Master page version
    Gravatar
    Commented on 4/16/2009 8:18 AM

    Ross - thanks so much. great solution. you ever come to the States in Asheville NC, the beer's on me....

  • # re: ASP.NET Text Character Counter – the Master page version
    Gravatar
    Commented on 7/30/2009 1:52 PM

    Excellent! Thanks for posting.

  • # re: ASP.NET Text Character Counter – the Master page version
    Gravatar
    Commented on 8/5/2009 11:10 PM

    if this field, <asp:TextBox ID="txtOutput" Text="160" runat="server" />
    is within the edit and insert templates of a form view how do you reference it in the javascript.

    I keep getting a compilation error..

    here is the javascript:
    <script language="javascript" type="text/javascript">
    function textCounter(field, countfield, maxlimit) {
    var output = document.getElementById(countfield);
    if (output == null) {return;}

    if (field.value.length > maxlimit)
    field.value = field.value.substring(0, maxlimit);
    else
    output.value = maxlimit - field.value.length;
    }
    </script>

  • # re: ASP.NET Text Character Counter – the Master page version
    Gravatar
    Commented on 10/28/2009 7:24 AM

    Another in a long and deserved line of thank yous (not sure of the grammar on that line, but I hope you get the sentiment).

  • # re: ASP.NET Text Character Counter – the Master page version
    Gravatar
    Commented on 12/21/2009 8:37 PM

    CSS and HTML files simultaneously in run time. This plug in provides callback for each of the files and in addition there is finally Callback which will be raised after all files are loaded and all callbacks are done.

  • # re: ASP.NET Text Character Counter – the Master page version
    Gravatar
    Commented on 4/7/2010 10:27 PM

    I'm trying to implement this in my application and I'm having a problem. In my view page when I call "Html.EditorForModel()", it displays nothing. However, when I call "Html.EditorFor(m => m.Property)" it displays the property perfectly. Am I doing something wrong or this a bug in the beta?

    Thanks !

    Trevor

  • # re: ASP.NET Text Character Counter – the Master page version
    Gravatar
    Commented on 4/25/2010 10:27 PM

    Thank u Sir,

    your code solved my problem.. Thank u very much... God Bless u.. :-)

  • # re: ASP.NET Text Character Counter – the Master page version
    Gravatar
    Commented on 5/29/2010 4:28 AM

    Oh God this is awesome, thank u very much

  • # re: ASP.NET Text Character Counter – the Master page version
    Gravatar
    Commented on 8/4/2010 9:03 PM

    Hi,

    Thankx a lot. This has got work for me.

    Mayur

  • # re: ASP.NET Text Character Counter – the Master page version
    Gravatar
    Commented on 10/12/2010 7:34 AM

    Your code worked great for counting my textareas.

    What do you suggest for getting the remaing count of the text field if there is already text in the field when the page loads?

  • # re: ASP.NET Text Character Counter – the Master page version
    Gravatar
    Commented on 12/28/2010 9:47 AM

    Thanks tons for this code. I was having a headache trying to make this type of thing work!

  • # re: ASP.NET Text Character Counter – the Master page version
    Gravatar
    Commented on 2/13/2011 1:05 PM

    How would you implement this in a usercontrol. It can't seem to find the ClientID no matter where I put it.

  • # re: ASP.NET Text Character Counter – the Master page version
    Gravatar
    Commented on 1/28/2012 7:43 PM

    thank you for this - every single other counter did not include the "this" for master pages. thank you so much - you saved me a lot of time.

  • # re: ASP.NET Text Character Counter – the Master page version
    Gravatar
    Commented on 3/29/2012 12:35 AM

    Thanks , u saved my day ure a god amongst insects !!!!

  • # re: ASP.NET Text Character Counter – the Master page version
    Gravatar
    Commented on 6/1/2012 9:40 AM

    Thank you for this code it’s very helpful. It works great for just a text box or an ASP text box.
    Now I have an AJAX extension on the text box and will no longer show a count. Would there be a fix for this?

  • # Works like a charm! =)
    Gravatar
    Commented on 7/8/2013 6:30 PM

    Thank you for this code!

  • # re: ASP.NET Text Character Counter – the Master page version
    Gravatar
    Commented on 8/1/2014 2:08 AM

    Awesome, have been stumped by javascript in a masterpage for some time now. Thansk

  • # re: ASP.NET Text Character Counter – the Master page version
    Gravatar
    Commented on 1/18/2017 5:58 AM

    Hi, I just wanted to say thanks for the simple yet effective code and explanations. This was really awesome.

    Is there away to make the output a label though?

  • # re: ASP.NET Text Character Counter – the Master page version
    Gravatar
    Commented on 1/19/2017 2:04 PM

    Hi Quique,

    Yep, you can easily modify the code sample to work with something else.

    However if you want to use an asp:Label and/or if you want to access the value in a postback then there's additional work you have to do.

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