Using jQuery to limit text length in multiline TextBox (asp.net)

In the code sample below , I will show how to use jQuery with asp.net to allow users to enter  predefined number of characters(eg: 250 character message in this case) in a multiline text box .You can use same logic for single line text boxes as well .The example also contains a dynamic counter which shows the number of text remaining .

The reason I had to come up with this solution is because I was having issues

text_box1

text_box2

HTML to create the controls

<asp:TextBox ID="giftmessage1" onKeyUp="Count(this,250);" onChange="Count(this,250);" TextMode="MultiLine" Rows="5" Columns="50" MaxLength="250" runat="server" />
          <asp:Label ID="lblRemainingLabel" Style="float:right;" runat="server">characters remaining</asp:Label>
          <span ID ="lblWordRemainingCount"   runat="server" ReadOnly="True">250</span>
          <asp:Label ID="lblMessageCharLimit" runat="server">Please limit  message to 250 characters</asp:Label>

Jquery logic that does the word count

<script type="text/javascript">     
          function Count(text,long)
         {
          var maxlength = new Number(long); 
          var remChar = maxlength – document.getElementById(‘<%=giftmessage1.ClientID%>’).value.length;
                    if (remChar > -1) {
              document.getElementById(‘<%=lblWordRemainingCount.ClientID%>’).innerHTML = remChar;
          }
          if (document.getElementById(‘<%=giftmessage1.ClientID%>’).value.length > maxlength)
           {
              text.value = text.value.substring(0, maxlength);
           }
         }
      </script>

 

Happy Coding Smile

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s