Welcome to Professional ASP.NET - Chris Love's Official Blog Sign in | Join | Help

Chris Love's Official ASP.NET Blog

Chris Love's Helpful tips, tricks and pragmatic development knowledge for the ASP.NET world.
Add to Technorati Favorites


ASP Insider Follow Me On Twitter
Creating a Twitter Like TextBox Character Warning Using JQuery

The other day I gave an intro to JQuery Lunch and Learn to my client’s development team. I walked them through creating a simple JQuery Plugin to create a character remaining feature like Twitter has on its web site.

The ingredients for this plugin involved a textarea field (but you could just use an input field if you really wanted) and assigning the plugin to the textarea.

<script src="jquery.limitcharacters.js" type="text/javascript"></script>
   1:  
   2:     <script type="text/javascript">
   3:         $(document).ready(function() {
   4:  
   5:         $('#txtWhatAreYouDoing').limitCharacters();
   6:  
   7:         });
</script> <textarea id="txtWhatAreYouDoing" name="txtWhatAreYouDoing" cols="50" rows="3"></textarea>

The plugin itself is composed of what I think of as 3 segments. The first allows you to define options, which as then mapped to an internal JavaScript object called settings with default values defined.

// Default settings
var settings = {
    charLimit: 50,
    showRemaining: true,
    remainingClass: 'remainingChars',
    remainingWarnClass: 'remainingCharsWarn'
};
if (options) {
    $.extend(settings, options);
}

The next section simply appends a SPAN to display the remaining characters as the user types in the field.

this.after("<span id='CharsLeft'></span>");

Now the real guts of the plugin! It intercepts the keyup event of the textarea and counts the number of characters used. If the number of characters is over the limit (settings.charLimit) it truncates to the maximum number of characters.

this.keyup(function() {
    var len = $(this).val().length;
    if (len > settings.charLimit) {
        this.value = this.value.substring(0, settings.charLimit);
    }

...

}

Next it gets the number of characters left and sets the value of the SPAN added earlier.

var charsLeft = settings.charLimit - len;

if (charsLeft < 0) {
    charsLeft = 0;
}

$('#CharsLeft').text(charsLeft + " characters left");

Finally it sets the style of the remaining character SPAN by determining if there are fewer than 10 characters remaining. It does this by leveraging the hasClass, addClass and removeClass JQuery utility methods.

if ((settings.charLimit - len) > 10) {
    if (!$('#CharsLeft').hasClass(settings.remainingClass)) {
        $('#CharsLeft').addClass(settings.remainingClass);
    }
    if ($('#CharsLeft').hasClass(settings.remainingWarnClass)) {
        $('#CharsLeft').removeClass(settings.remainingWarnClass);
    }
} else {
    if (!$('#CharsLeft').hasClass(settings.remainingWarnClass)) {
        $('#CharsLeft').addClass(settings.remainingWarnClass);
    }
}

The CSS classes used look like this:

.remainingChars
{
    font-family: Arial, Helvetica, sans-serif;
    font-size: 2.5em;
    font-weight: bold;
    color: #666666;
}

.remainingCharsWarn
{
    color: #660033;
}

Putting it all together gives us a nice little plugin.

The full plugin source:

jQuery.fn.limitCharacters = function(options) {

    if (this.length == 0) return;

    // Default settings
    var settings = {
        charLimit: 50,
        showRemaining: true,
        remainingClass: 'remainingChars',
        remainingWarnClass: 'remainingCharsWarn'
    };
    if (options) {
        $.extend(settings, options);
    }

    this.after("<span id='CharsLeft'></span>");

    this.keyup(function() {
        var len = $(this).val().length;
        if (len > settings.charLimit) {
            this.value = this.value.substring(0, settings.charLimit);
        }

        var charsLeft = settings.charLimit - len;

        if (charsLeft < 0) {
            charsLeft = 0;
        }

        $('#CharsLeft').text(charsLeft + " characters left");

        if ((settings.charLimit - len) > 10) {
            if (!$('#CharsLeft').hasClass(settings.remainingClass)) {
                $('#CharsLeft').addClass(settings.remainingClass);
            }
            if ($('#CharsLeft').hasClass(settings.remainingWarnClass)) {
                $('#CharsLeft').removeClass(settings.remainingWarnClass);
            }

        } else {

            if (!$('#CharsLeft').hasClass(settings.remainingWarnClass)) {
                $('#CharsLeft').addClass(settings.remainingWarnClass);
            }

        }

        return this;

    });


}
Posted: Tuesday, December 08, 2009 7:34 PM

by Chris Love
Filed under: , ,

Comments

brian trane said:

Excellent post quite helpful for me i have learn so much from this tutorial please keep it up thank you very much for the informative post.
# January 19, 2010 12:08 AM

Michael said:

Hey Chris, thanks for this handy bit of code. For some reason, the countdown shows up, but won't countdown the characters left. In Firebug, I get "detailed error: The 'charCode' property of a keyup event should not be used. The value is meaningless." for every keystroke. any ideas why? thanks again, Michael
# May 21, 2010 2:49 PM

Ketan Thakkar said:

Well there is a bug in the plugin-source code you have pasted. if ((settings.charLimit - len) > 10) { if (!$('#CharsLeft').hasClass(settings.remainingClass)) { $('#CharsLeft').addClass(settings.remainingClass); } if ($('#CharsLeft').hasClass(settings.remainingWarnClass)) { $('#CharsLeft').removeClass(settings.remainingWarnClass); } } else { if (!$('#CharsLeft').hasClass(settings.remainingWarnClass)) { $('#CharsLeft').addClass(settings.remainingWarnClass); } This logic is wrong.------------------------------ This is right (as below)-------------------- if ((settings.charLimit - len) > 10) { if ($('#CharsLeft').hasClass(settings.remainingWarnClass)) { $('#CharsLeft').removeClass(settings.remainingWarnClass); } if (!$('#CharsLeft').hasClass(settings.remainingClass)) { $('#CharsLeft').addClass(settings.remainingClass); } } else { if (!$('#CharsLeft').hasClass(settings.remainingClass)) { $('#CharsLeft').removeClass(settings.remainingClass); } if (!$('#CharsLeft').hasClass(settings.remainingWarnClass)) { $('#CharsLeft').addClass(settings.remainingWarnClass); } } (a bit inefficient but works very well) Thanks for the 98% work, I just added my 2 (per)cent to it. :-)
# May 27, 2010 1:13 PM
Leave a Comment

(required) 

(required) 

(optional)

(required) 

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS