Friday, October 15, 2010

Set Max Length for ASP.NET MultiLine Textbox using jQuery

ASP.NET textbox has a property called "MaxLength", which restrict the end-user from entering characters beyond specified MaxLength. This property works like a charm for ASP.NET textbox but it does not work with ASP.NET MultiLine textbox. In this post, I will show you how we can implement Maxlength property for ASP.NET MultiLine textbox using jQuery. Let's first create a multiline textbox.
<asp:TextBox ID="txtValue" runat="server" TextMode="MultiLine" Rows="10" Columns="50"></asp:TextBox>
To restrict user from entering characters beyond a certain limit, we will use keypress() event of multiline textbox. For demo purpose, I have set the maxlenght to 250. You can change as per your need.
$(document).ready(function()
{
   var MaxLength = 250;
   $('#txtValue').keypress(function(e)
   {
      if ($(this).val().length >= MaxLength) {
      e.preventDefault();}
   });
});
In keypress event code, we check the lenght of text(which is already in textbox) and if the length is beyond the maxlength variable value then it is not getting appended in the textbox. Simple and easily achieved with few lines of code. But it would be nice, if we can show the end user that how many character are entered in the textbox. See below image.


Well, all you need to do is to place a label below the textbox with the default text as "Allowed only 250 characters."
<asp:Label ID="lblCount" runat="server" Text="Allowed only 250 characters." 
Font-Size="Smaller" Font-Names="Arial"> </asp:Label>
Now, to show how many characters end user has entered, we will use keyup() event of multiline textbox. This event will take the count of currently entered characters in textbox and modifies the value of the label.
$('#txtValue').keyup(function(){
  var total = parseInt($(this).val().length);
  $("#lblCount").html('Characters entered <b>' + total + '</b> out of 250.');
});
Simple and cool, isn't it? But there is one issue here which is that it will not work with copy-paste. To fix this issue, disable pasting of the text in the textbox. Just add onpaste="return false;" event in the text box and pasting will be disabled.
<asp:TextBox ID="txtValue" runat="server" TextMode="MultiLine" Rows="10" onpaste="return false;" Columns="50"></asp:TextBox>
See live Demo and Code
Feel free to contact me for any help related to jQuery. I will gladly help you.