in

ASP.NET Weblogs

Gregory Rubinstein

Remaining Characters Counter

Recently I was developing a webform (asp.net) where the user could submit his feedback, and one of the requirements was that the user should not enter more than a set number of characters in his message, so I thought it would be real nice for the end user to know how many more characters he still can type until the maximum limit is reached.

In order to allow that functionality, I created a asp.net multiline textbox for text input and an html readonly text field (for displaying number of characters until the maximum).

Then, I created a Javascript function and called it every time the contents of the multiline textbox changed (onKeyUp and onChange events).

Below is the code:

<html>
<head>

<script language="JavaScript">

function CountChars(text,long)
{
var maxlength = new Number(long);
var myLength = text.value.length;
document.forms[0].Counter.value = maxlength - myLength;
if (myLength > maxlength) {
text.value = text.value.substring(0,maxlength);
}
}
</script>

</head>
<body>

<form id="Form1" runat="server">

<asp:Textbox mode="multiline" id="txtMessage" runat="server" /><br />

<input type="text" name="Counter" readonly="readonly" />

</form>

</body>
</html>

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    Util.SetTextBoxProperties(txtMessage, True)
End Sub

Below is the SetTextBoxProperties method, which actually did the work:

Public Sub SetTextBoxProperties(ByVal txt As TextBox)
    txt.Attributes.Add("onKeyUp", "CountChars(this," & txt.MaxLength & ")")
    txt.Attributes.Add("onChange", "CountChars(this," & txt.MaxLength & ")")

End Sub

Comments

 

Anon said:

Excellent, Works straight out of the box.

Ta

April 14, 2008 10:13 PM
 

gaurav said:

this is a good implementations but the bad part is the copy and paste through mouse.

this does not work for mouse event

November 27, 2008 5:21 AM
 

Thuan V. Nguyen said:

thanx for the code it worked perfectly.

didn't need this though...

Util.SetTextBoxProperties(txtMessage, True)

only needed...

SetTextBoxProperties(txtMessage)

December 15, 2008 8:04 PM
 

Jonathan said:

There are other ways to catch copy and paste through the mouse such as placing a custom length validator on the asp:Textbox control. They are very simple and straightforward to make.

Excellent post, though, Greg!

April 6, 2009 10:42 AM

Leave a Comment

(required)  
(optional)
(required)  
Add