December 29, 2010

Max length of multiline TextBox and TextArea

It is a common scenario to have a textarea element  or multiline TextBox control in a html / asp.net page and the challenge is to limit the number of characters that can be entered and to display the remaining number of characters that can be entered. The textarea unlike the TextBox control does not support the maxlength property and thus cannot be limited. The solution is to use javascript to limit the number of characters.

In this example, I have added a TextBox control and added the onkeyup event for the control. The code for the page is below.

aspx
  1. <asp:TextBox ID="T1" runat="server" TextMode="MultiLine" Rows="3" onkeyup="T1_KeyUp()"></asp:TextBox>
  2. <span id="T1Status" style="color:Red;">50 character(s) remaining.</span>

The span element in the page will display the number of remaining characters that can be entered in the TextBox.

The JavaScript code is below. The code sets the max length of the TextBox to 50 characters.

JavaScript function
  1. <script type="text/javascript">
  2.     function T1_KeyUp() {
  3.         var text = document.getElementById('<%= T1.ClientID %>').value;
  4.         var len = text.length;
  5.         var max = 50;
  6.         if (len > max) {
  7.             text = text.substring(0, max);
  8.             len = 50;
  9.             document.getElementById('<%= T1.ClientID %>').value = text;
  10.         }
  11.         document.getElementById('T1Status').innerHTML = max - len + " character(s) remaining.";
  12.     
  13.     }
  14. </script>

Server side could also be used for this but it will cause unnecessary postbacks to the server. However, the actual text entered should be validated from the server end as JavaScript can be easily disabled by a user.

0 comments: