Posted  14 Dec 2008 - 13:41:44

Category: JavaScript

Create a textbox char counter in

You want to create a counter for the user to keep track of how much they can still write in a textbox.

This will all be done client side, no need to call the server for something the client already knows. First we need a JavaScript function in the ASP page:

function getLength(e, d)
 if (d != null && e != null)
  var maxLength = 4096;
  d.innerHTML = maxLength - e.value.length;

In the Page_Load function, use this code piece to create the call to the script for this control you want to base the counting on.

this.txtComment.Attributes.Add("onkeyup", "getLength(this, document.getElementById('commentCount'))");

The second argument in this call (commentCount) is a span, that does not run on the server. If you really need it to run on the server you need to use ClientID to get the real client id when running the application. If you don't need to call it from code, you can just hard code it just like in the example above.

The script can be altered to reflect your needs, you could loose the maxLength variable and just display the count. For a comment field like this though it makes more sense to show how many chars can still be used.

Marked as helpful by 2 users


© SolutionCottage 2008-2011 9/23/2017 11:51:28 AM