Geeks With Blogs
Rajesh Pillai My experiments with mvc, jquery, wpf, silverlight, sharepoint, tdd and design patterns.

Lets quickly have a look at how you can limit the entry to textbox and display the character input left to be keyed in.

First things first, the script.

<script type="text/javascript">
    $(function() {
        var limit = 250;
        $('#dvLimit').text('250 characters left');
        $('textarea[id$=txtDemoLimit]').keyup(function() {
            var len = $(this).val().length;
            if (len > limit) {
                this.value = this.value.substring(0, limit);
            $("#dvLimit").text(limit - len + " characters left");

The $() function does the following things on startup.

1. Set a variable to a limit of 250 characters.

2. Assign a default value to the "div" element with id "dvLimit"

3. Find the control that contains the id "txtDemoLimit" and hook up the keyup event.

4. In the keyup event get the length of the current text.

5. If len is greater than the limit set, set the text value as a substring within the specified limit.

6. Update the div with the no. of characters left to be keyed in.

The HTML is shown below.

<div id="dvLimit"></div>
    <asp:TextBox ID="txtDemoLimit" TextMode="MultiLine" Columns = "40" Rows = "10" runat="server"></asp:TextBox>

The following is the application in action.

Jquery text box limit demo


Modify this as per your requiement and enjoy jQuerying !!!


<a href="" style="display:none" rel="tag">CodeProject</a>
Posted on Thursday, December 3, 2009 5:40 PM jQuery , | Back to top

Comments on this post: jQuery Limit text entry

No comments posted yet.
Your comment:
 (will show your gravatar)

Copyright © Rajesh Pillai | Powered by: