CODEDIGEST
Home » CodeDigest
Search
 

Technologies
 

Limit Number of Characters in MultiLine ASP.Net TextBox or TextArea Using jQuery
Submitted By Satheesh Babu B
On 1/11/2010 8:16:40 AM
Tags: ASP.Net,CodeDigest,jQuery  

Limit Number of Characters in MultiLine ASP.Net TextBox or TextArea Using jQuery


 
The following jQuery script can be used to limit the number of characters in the ASP.Net multiline trextbox.

Download the latest jQuery library from jQuery.com and integrate into your project. Read the following FAQ's to integrate jQuery library to your project.

What is jQuery? How to use it in ASP.Net Pages?

How to enable jQuery intellisense in Visual Studio 2008?

How to use jQuery intellisense in an external javascript file?

The below script can be used to limit the number characters. Just set a maximum limit of no of characters to the variable MaxLength in the below code.

<script src="_scripts/jquery-1.3.2.min.js" type="text/javascript"></script>
    <script language="javascript">
        $(document).ready(function() {
        //Set the Variable for max length
        var MaxLength = 100;
            
            
            $('#TextBox1').keyup(function() {
                if ($(this).text().length > MaxLength) {
                    $(this).text($(this).text().substring(0, MaxLength));
                }               
            });
          
        });

 </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
<asp:TextBox
ID="TextBox1" runat="server"
TextMode="MultiLine" Rows="10"></asp:TextBox>
   </div>

    </form>
</body>
</html>

The above function will restrict the users from typing more than 100 characters in the textbox but it does not validate the maximum length when the user drags the content from other pages or from same page into the text box. i.e. select a paragraph and drag it into the textarea. To over come this, define a blur event and include the same code.

$('#TextBox1').blur(function() {
                if ($(this).text().length > MaxLength) {
                    $(this).text($(this).text().substring(0, MaxLength));
                }              
            });


Happy Coding!!

Do you have a working code that can be used by anyone? Submit it here. It may help someone in the community!!

Recent Codes
  • View All Codes..