Multi-line Textbox Character Counter

In this article you would learn how create an ASP.NET user control with jQuery which displays the character count of a multi-line textbox below it. The user control takes the character limit as one of its properties. Below is the markup of my usercontrol:

Below is the jQuery code I have used in the user control:

$(document).ready(function() {
        $('#<%=tbMultiLine.ClientID %>').keyup(function(e) {
            var limit = $('#<%=hdnCharacterLimit.ClientID %>').val();
            var tbLength = $(this).val().length;
            if (tbLength > limit) {
                this.value = this.value.substring(0, limit);
            $('#<%=lblCharCount.ClientID %>').show();
            $('#<%=lblCharCount.ClientID %>').text($(this).val().length + '/' + $('#<%=hdnCharacterLimit.ClientID %>').val() + ' characters');

When the DOM is ready I add a keyup event to the multi-line textbox and get the character limit from a hidden field in the user control. I then check to see if the character count is greater than the limit and if so then I remove the additional characters and prevent the default action for the textbox.


Download Code

kick it on

Shout it

blog comments powered by Disqus