SIGN UP MEMBER LOGIN:    
ARTICLE

Limit number of characters in TextBox control

Posted by Bryian Tan Articles | ASP.NET Programming May 20, 2010
In this article we will see how to limit/count number of characters in TextBox control.
Reader Level:

Introduction

Recently, I was revisiting the JavaScript used to limit the number of characters in a TextBox control. This client-side script utilized document.getElementById method and the control ID for HTML markup that was generated by ASP.NET. The problem with this script was that it did not work correctly with multiple TextBox controls on the web page and not cross-browser compatible. So I decided to rewrite it to ease the mentioned problems. Shown in Listing 1 is the new content of the JavaScript. There are two functions resided in it namely validateLimit and get_object. The former function accepts three parameters.

1. TextBox object
2. HTML Div id (to hold the text)
3. Maximum number of characters the TextBox control can hold

The purpose of the later function is to ensure that modern and older browsers are able to access the form elements.

Listing 1

function validateLimit(obj, divID, maxchar) {
    objDiv = get_object(divID);
    if (this.id) obj = this;
    var remaningChar = maxchar - obj.value.length;
   if (objDiv){
        objDiv.innerHTML = remaningChar + " characters left";
    }
    if (remaningChar <= 0) {
        obj.value = obj.value.substring(maxchar, 0);
        if(objDiv) {
            objDiv.innerHTML = "0 characters left";
        }
        return false;
    }
    else
    { return true; }
}
function get_object(id) {
    var object= null;
    if (document.layers) {
        object = document.layers[id];
    } else if (document.all) {
        object = document.all[id];
    } else if (document.getElementById) {
        object = document.getElementById(id);
    }
    return object;
}

Putting everything together.

Listing 2

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Without master page</title>
     <script type="text/javascript" src="js/JScript.js" ></script>
</head>
<body>
    <form id="form1" runat="server">
     <div> <br />
    <div id="lblMsg1">240 characters left</div>
    <asp:TextBox ID="TextBox1" runat="server" Height="50px" MaxLength="240" 
        TextMode="MultiLine" Width="600px" ToolTip="Summary:(240 characters)" 
                    onkeyup="return validateLimit(this, 'lblMsg1', 240)"/>
        <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
            ControlToValidate="TextBox1" Display="Dynamic" 
            SetFocusOnError="True">*</asp:RequiredFieldValidator>
    <br /><br /><br />
    <div id="lblMsg2">300 characters left</div>
    <asp:TextBox ID="TextBox2" runat="server" Height="50px" MaxLength="300" 
        TextMode="MultiLine" Width="600px" ToolTip="Summary:(300 characters)" 
                    onkeyup="return validateLimit(this, 'lblMsg2', 300)"/>
        <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server"
            ControlToValidate="TextBox2" Display="Dynamic" 
            SetFocusOnError="True">*</asp:RequiredFieldValidator>
    <br /> <br />
    <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
    <br />
    </div>
    </form>
</body>
</html>

Here is the output:

Figure 1

characters count

History

  • May 20, 2010: First release.
  • May 20, 2010
    • Added new function trimEnter to replace enter key with empty string.

Conclusion

If you find any bugs or disagree with the contents, please drop me a line and I'll work with you to correct it. I would suggest downloading the demo and explore it in order to grasp the full concept of it because I might left out some useful information.

IE, Firefox, Google Chrome, Safari

Tested on IE 6.0/7.0/8.0, Google Chrome, Firefox, Safari

Resources

document.getElementById On All Browsers – Cross browser getElementById
Modifying Strings with Regular Expressions

Watch this script in action

Demo

Downloads

Download

Login to add your contents and source code to this article
share this article :
post comment
 

Just my opinion -- in striving for elegant software design is to eliminate code like javascript that has a risk of cross-platform incompatibility, adds more script to be rendered in the browser, uses unnecessary bandwith as a result and creates a potential maintenance issue.  Javascript has it's place but for limiting characters it is better to set the property for the core framework, and let ASP.Net take care of the rendering, that way it always works in all browsers and does not send and extra block of Javascript to the browser for each page.

Posted by bailey May 31, 2010

I don't see any problem with MaxLength, the approach I mentioned make the page more interactive.

Posted by Bryian Tan May 30, 2010

Just curious, why this approach instead of just setting the Maxlength property?

Posted by bailey May 30, 2010

thanks.

Posted by Bryian Tan May 20, 2010

thank you for your document.

Posted by Maulik Patel May 20, 2010
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
PREMIUM SPONSORS
  • Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites - Click Here!
    ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications. Visit DynamicPDF here
Become a Sponsor