Introduction
While contemplating a project at work, I realized it would be useful to give users feedback on the number of characters remaining for text area controls with a set maximum length. Originally, I set out to create inline code that could perform the task, however, with a little tweaking, I found the code works better as a re-usable User Control. The code for the control is very simple:
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
txtCount.Text = txtInput.MaxLength.ToString();
txtInput.Attributes.Add("onKeyUp",
"javascript:document.getElementById('"+ txtCount.ClientID +
"').setAttribute('value', (" + txtInput.MaxLength +
" - parseInt(document.getElementById('" + txtInput.ClientID +
"').getAttribute('value').length)));");
}
public int MaxLength
{
get { return txtInput.MaxLength; }
set { txtInput.MaxLength = value; }
}
</script>
<table>
<tr>
<td>
<asp:Label ID="Label1" runat="server">Characters Left: </asp:Label>
<asp:TextBox ID="txtCount" runat="server"
BorderStyle="None" ReadOnly="True">0</asp:TextBox>
</td>
</tr>
<tr>
<td>
<asp:TextBox ID=txtInput runat="server" BorderColor="Gray"
BorderStyle="Solid" BorderWidth="1px"
Height="125px" MaxLength="2000"
TextMode="MultiLine"
Width="350px"></asp:TextBox>
</td>
</tr>
</table>
The bulk of the work is done in the Page_Load
event. Using the Attributes
collection, I added an OnKeyUp
event that gets the length of the input text, subtracts that from the maximum length allowed by the input textbox control, and displays it in another text box. Because the JavaScript works off the ID of the control, and ASP.NET dynamically assigns unique IDs to each control generated, you can have dozens of these on a page and each will track only its own contents.
To round out the control, I would suggest exposing some properties of the underlying controls through public properties of the user control (such as MaxLength
, above), so the control can be configured separately for different pages/sites.
Caveat
Because the TextArea
HTML control does not support MaxLength
, the JavaScript will not prevent a user from entering more characters. However, you can check against the MaxLength
property for validation purposes, or simply truncate the excess text when processing the form.