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)

 Print | Posted on Saturday, February 07, 2009 5:53 PM |



Feedback

Gravatar

# re: ASP.NET Text Character Counter – the Master page version

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

2/10/2009 10:12 AM | Jack

Gravatar

# re: ASP.NET Text Character Counter – the Master page version

Nice one Ross... does the job perfectly!

2/10/2009 9:11 PM | AJones

Gravatar

# re: ASP.NET Text Character Counter – the Master page version

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!

4/1/2009 3:23 AM | Laban

Gravatar

# re: ASP.NET Text Character Counter – the Master page version

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.

4/13/2009 11:02 AM | Jonathan

Gravatar

# re: ASP.NET Text Character Counter – the Master page version

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

4/16/2009 8:18 AM | Janet

Gravatar

# re: ASP.NET Text Character Counter – the Master page version

Excellent! Thanks for posting.

7/30/2009 1:52 PM | Frank

Gravatar

# re: ASP.NET Text Character Counter – the Master page version

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>

8/5/2009 11:10 PM | Kevin Giles

Gravatar

# re: ASP.NET Text Character Counter – the Master page version

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

10/28/2009 7:24 AM | kannankeril

Gravatar

# re: ASP.NET Text Character Counter – the Master page version

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.

12/21/2009 8:37 PM | www.bravovegas.com/

Gravatar

# re: ASP.NET Text Character Counter – the Master page version

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

4/7/2010 10:27 PM | computer repairs gold coast

Gravatar

# re: ASP.NET Text Character Counter – the Master page version

Thank u Sir,

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

4/25/2010 10:27 PM | Nitin

Gravatar

# re: ASP.NET Text Character Counter – the Master page version

Oh God this is awesome, thank u very much

5/29/2010 4:28 AM | Justme

Gravatar

# re: ASP.NET Text Character Counter – the Master page version

Hi,

Thankx a lot. This has got work for me.

Mayur

8/4/2010 9:03 PM | Mayur nirmal

Gravatar

# re: ASP.NET Text Character Counter – the Master page version

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?

10/12/2010 7:34 AM | jmilton

Gravatar

# re: ASP.NET Text Character Counter – the Master page version

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

12/28/2010 9:47 AM | kdavidso

Gravatar

# re: ASP.NET Text Character Counter – the Master page version

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

2/13/2011 1:05 PM | Craig


Post Comment

Title  
Name  
Email
Website / Url
 

Your comment

   
Ensure the word in this box says 'orange':
 
Please add 2 and 7 and type the answer here:





Due to excessive comment spam, all comments are now being moderated. If you're a comment spammer then you're wasting your time here. Your comments will not be published - ever.


About me

My name is Ross Hawkins and I'm a developer, consultant, business owner and writer based in Auckland, New Zealand (pictured below!). My current work revolves around ASP.NET, C#, jQuery, Ajax, SQL Server, and a mix of other Microsoft development technologies.

I also have about 15 years of experience with IBM Lotus Notes/Domino and associated technologies. While Notes/Domino is no longer my primary focus I still like to dabble and keep my skills up to date.

I own and run 2 businesses - Hawkins Consulting Services, and Ignition Development.

Bethells Beach, located in sunny West Auckland, New Zealand




Subscribe

Subscribe to this feed


Search




Popular Content

Troubleshooting WebResource.axd

The .NET 2.0 framework changed the way clientside JavaScript is delivered to the browser. Previously, ASP.NET 1.1 used the aspnet_client directory whereas now 2.0 uses WebResource.axd.

Published on October 8, 2006

Microsoft AJAX Extensions: Sys.Debug is null or not an object

One of the breaking changes which was made with the 1.0 release of the Microsoft Ajax Extensions was the renaming of the 'Debug' class to 'Sys.Debug' for reasons of compatiability with other frameworks. Breaking changes like this can often be a source of frustration..

Published on May 22, 2007

Simple ASP.NET 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

Published on December 4, 2006

Simple ASP.NET Character Counter - with Master Page Support

A quick update to my previous character counter article adding some changes for those using it with Master Pages.

Published on February 7th, 2009

Adding Tooltips to Gridview Headers

As the title says, this is a very simple but dynamic way of achieving tooltip text on a header column. It's not overly flash, but it's lightweight and quick to implement.

Published on April 15, 2007

SQL Server Web Report Viewer Issues on Windows 2008 Server/IIS7

A fix for another AXD related issue, this time with the SQL Server Web Report Viewer Control which was being served up via IIS7 on a Windows 2008 server.

Published on June 2, 2007
Updated on April 10, 2008




Archives

January, 2012 (3)
December, 2011 (3)
November, 2011 (8)
October, 2011 (9)
September, 2011 (8)
August, 2011 (5)
July, 2011 (4)
June, 2011 (7)
May, 2011 (5)
April, 2011 (3)
March, 2011 (8)
February, 2011 (4)
January, 2011 (3)
December, 2010 (8)
November, 2010 (5)
October, 2010 (6)
September, 2010 (7)
August, 2010 (11)
July, 2010 (12)
June, 2010 (8)
May, 2010 (8)
April, 2010 (4)
March, 2010 (8)
February, 2010 (6)
January, 2010 (12)
December, 2009 (13)
November, 2009 (11)
October, 2009 (12)
September, 2009 (12)
August, 2009 (2)
July, 2009 (7)
June, 2009 (12)
May, 2009 (9)
April, 2009 (9)
March, 2009 (9)
February, 2009 (8)
January, 2009 (7)
December, 2008 (6)
November, 2008 (7)
October, 2008 (9)
September, 2008 (12)
August, 2008 (9)
July, 2008 (6)
June, 2008 (24)
May, 2008 (13)
April, 2008 (16)
March, 2008 (8)
February, 2008 (10)
January, 2008 (1)
December, 2007 (14)
November, 2007 (11)
October, 2007 (11)
September, 2007 (13)
August, 2007 (11)
July, 2007 (5)
June, 2007 (15)
May, 2007 (11)
April, 2007 (9)
March, 2007 (9)
February, 2007 (10)
January, 2007 (8)
December, 2006 (18)
November, 2006 (11)
October, 2006 (14)
September, 2006 (9)
August, 2006 (10)
July, 2006 (4)
June, 2006 (4)
May, 2006 (6)
April, 2006 (3)
February, 2006 (6)
January, 2006 (10)
September, 2005 (2)
August, 2005 (4)

Post Categories

ASP.NET
AJAX
Amusing
NZ
NZ Trains
Notes/Domino
Visual Studio
Web Development
Miscellaneous
Me
Rugby
C#
SQL