Limit Number Of Characters In an ASP.NET Multiline TextBox using jQuery

Posted by: Suprotim Agarwal , on 10/8/2009, in Category jQuery and ASP.NET
Views: 108531
Abstract: This article shows you how to limit characters entered in an ASP.NET Multiline TextBox. The ASP.NET Multiline TextBox ignores the MaxLength property. So one of the ways of solving this requirement is to use Client Script and detect if the maximum character limit of the Multiline TextBox has been reached.
Limit Number Of Characters In an ASP.NET Multiline TextBox using jQuery
 
This article shows you how to limit characters entered in an ASP.NET Multiline TextBox. The ASP.NET Multiline TextBox ignores the MaxLength property. So one of the ways of solving this requirement is to use Client Script and detect if the maximum character limit of the Multiline TextBox has been reached. I will be showing a common technique adopted by developers to solve this requirement. I will then explain why this technique is not user friendly and how to improve on it.
This article is a sample chapter from my EBook called 51 Tips, Tricks and Recipes with jQuery and ASP.NET Controls. The chapter content has been modified to publish it as an article. Also please note that for demonstration purposes, I have included both the JavaScript and CSS into the same file. Ideally, these resources should be created in seperate folders for maintainability.
A common technique adopted by developers is to capture the textbox keyup event and calculate the number of characters in the textbox, as the user types in it. If the character exceeds the limit of the textbox (in our case 50 characters), the additional characters entered by the user is disallowed.  The code is as shown below:
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Limit Characters in a Multiline TextBox</title>
    <script type='text/javascript'
    src='http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js'>
    </script>
 
    <script type="text/javascript">
        $(function() {
            var limit = 50;
 
            $('textarea[id$=tb1]').keyup(function() {
                var len = $(this).val().length;
                if (len > limit) {
                    this.value = this.value.substring(0, limit);
                }
                $('#spn).text(limit - len + " characters left");
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="tb1" runat="server" TextMode="MultiLine"/><br /> 
        <span id="spn "></span>     
    </div>
    </form>
</body>
</html>
Observe how we are selecting the control using textarea in the code shown above $('textarea[id$=tb1]'). This is as the ASP.NET Multiline TextBox renders as a textarea.
Although the solution given above restricts the user from entering more than 50 characters, this behavior can be confusing for users who may not realize that they have reached the TextBox limit. Instead of disallowing extra characters, a slick way of handling this requirement would be to visually indicate to the user when the textbox limit has been exceeded. Then before submitting the form, give the user a chance to remove the extra text. The code shown below changes the background color of the textbox to red when the textbox limit is exceeded. The user is also prevented from submitting the form.
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Limit Characters in a Multiline TextBox</title>
    <script type='text/javascript'
    src='http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js'>
    </script>
    <style type="text/css">
    .exceeded{
        background-color:red;
    }
    </style>
   
    <script type="text/javascript">
        $(function() {
            var limit = 50;
            var tb = $('textarea[id$=tb1]');
            $(tb).keyup(function() {
                var len = $(this).val().length;
                if (len > limit) {
                    //this.value = this.value.substring(0, 50);
                    $(this).addClass('exceeded');
                    $('#spn').text(len - limit + " characters exceeded");
                }
                else {
                    $(this).removeClass('exceeded');
                    $('#spn').text(limit - len + " characters left");
                }
            });
 
            $('input[id$=btnSubmit]').click(function(e) {
                var len = $(tb).val().length;
                if (len > limit) {
                    e.preventDefault();
                }
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div class="smallDiv">
        <h2>Type into this textbox which accepts 50 characters overall</h2>
        <asp:TextBox ID="tb1" runat="server" TextMode="MultiLine"/><br />
        (This textbox accepts only 50 characters) <br />
        <span id="spn"></span> <br />
        <asp:Button ID="btnSubmit" runat="server" Text="Submit"/>
        <span id="error"></span>
        <br /><br />
        Tip: Clicking on the Submit button when number of characters are
        less than 50, results in a postback to same page. If you exceed 50
        characters, the exceeded characters are printed below the textbox
        and a postback is prevented.
    </div>
    </form>
</body>
</html>
When the number of characters exceeds the textbox limit, we add the exceeded class to the textbox, which turns the textbox background to red, indicating the user that the limit has been exceeded. The result is shown here:
LimitExceeded
When the user tries and submits the form now, the length of the TextBox is calculated and the user is prevented from submitting the form, since the textbox exceeds the permissible length. 
When the user removes the extra text, the exceeded class is removed. The result is shown here:
RemoveExceeded
The form can now be submitted. You can see a Live Demo here . This demo has been tested on IE7, IE8, Firefox 3, Chrome 2 and Safari 4.
There are plenty of such similar tips that I will be covering in my upcoming EBook over here 51 Tips, Tricks and Recipes with jQuery and ASP.NET Controls
I hope you liked this article and I thank you for viewing it.
If you liked the article,  Subscribe to the RSS Feed or Subscribe Via Email  

This article has been editorially reviewed by Suprotim Agarwal.

Absolutely Awesome Book on C# and .NET

C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.

We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).

Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.

Click here to Explore the Table of Contents or Download Sample Chapters!

What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

Author
Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigious Microsoft MVP award for Sixteen consecutive years. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that offers Digital Marketing and Branding services to businesses, both in a start-up and enterprise environment.

Get in touch with him on Twitter @suprotimagarwal or at LinkedIn



Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by Mik on Monday, October 12, 2009 3:55 AM
Hi!
Why don't you use MaxLength property for asp:TextBox
It will generate Html imput field with like this
<input name="td" type="text" maxlength="50" id="td" />
and browser will limit maximum number of characters for this fields.
Comment posted by Sean on Monday, October 12, 2009 7:31 PM
Because MaxLength property does not work when dealing with a textbox that is multi-line.
Comment posted by joe on Saturday, October 24, 2009 1:59 AM
i think you're counting Enter key presses wrong in IE vs FF.

this guy ran into the same thing in his maxlength plugin (luckily someone posted a fix in the comments):
http://remysharp.com/2008/06/30/maxlength-plugin/
Comment posted by Suprotim Agarwal on Wednesday, October 28, 2009 9:44 AM
Joe: Thanks for that link. I will check it out!
Comment posted by AaronLS on Friday, January 14, 2011 5:53 PM
Looks like you have a typo here, missing a closing apaostrophe:
$('#spn).text(limit - len + " characters left");
Comment posted by nbmbm on Tuesday, March 1, 2011 3:59 AM
nbmm,,mnn
Comment posted by ganapathy on Tuesday, March 1, 2011 4:00 AM
ggfhfghh
Comment posted by goq on Tuesday, January 3, 2012 5:47 AM
hey thx this did the trick for me ;-)
Comment posted by NeverKnow on Monday, August 12, 2013 11:07 AM
great work ! Thanks a lot :)
Comment posted by udhaya on Wednesday, February 12, 2014 7:31 AM
u
Comment posted by Vinay on Sunday, June 15, 2014 3:46 AM
Nice one.
http://www.aspdotnet-pools.com/2014/06/restrict-number-of-characters-to-be.html