Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / Javascript

Plugin for Textarea's MaxLength Validation

5.00/5 (1 vote)
14 Jan 2014CPOL 8.6K  
A plugin to do the textarea's maxlength validation

Introduction

If you are using textbox, then you have the freedom to restrict the amount of data that a user can enter by using MaxLength attribute.

But if you are using a textarea, then there is no default support for this. In this tip, I will discuss how to create a textarea plugin in jQuery which will serve the purpose.

Background

HTML Textarea does not provide any default support for the maximum length that can be entered into it. So to achieve this, I am going to write a jQuery plugin.

Pages

  1. One HTML Page
  2. jQuery library file
  3. Below jQuery TruncateLength plugin.

Using the Code

JavaScript
(function($){
    $.fn.truncateLength = function(options) {
        var defaults = { // Default properties of the plugin.
            fontSize: 10,
            backColor: '#FAFAB2',
            foreColor: '#FF0000',
            fadeinTime: 500,
            fadeoutTime: 1500,
            maxLength: 100,
            overrideStyle: false,
            cssClass: ''
        };

        var opt = $.extend(defaults, options);

        return this.each(function() {
            var me = $(this);

            if(me.is('textarea')) { // If it is textarea then only apply the plugin
                me.keyup(truncateText);
                var maxLength = parseInt(opt.maxLength); // Collect the max length value.

                function truncateText(e) {
                    if(!isNaN(maxLength) && me.val().length > maxLength) {
                        var cell = { // Get the Height, Width, Top & left position of the textarea.
                            Height: me[0].offsetHeight,
                            Width: me[0].offsetWidth,
                            Top: me.offset().top,
                            Left: me.offset().left
                        };

                        var truncatedText = me.val().substring(0, maxLength); // Truncate the text.
                        //Create a popup which will be placed on the textbox, 
                        //which will contain the validation message.
                        var popup = $('<p />').html('Max limit reached (' + maxLength + ' chars).')
                                              .css({
                                                'top': cell.Top + 'px', 'left': cell.Left + 'px',
                                                'height': cell.Height + 'px', 'width': cell.Width + 'px',
                                                'position': 'absolute', 'display': 'none'
                                              });

                        // If class is attached with the popup then add it else add default styles.
                        if(opt.overrideStyle && opt.cssClass) {
                            popup.addClass(opt.cssClass);
                        } else {
                            popup.css({
                                'background-color': opt.backColor, 'color': opt.foreColor,
                                'font-size': opt.fontSize + 'px', 'text-align': 'center',
                                'line-height': cell.Height + 'px', 'z-index': '1001'
                            });
                        }

                        // show the popup message for some time and then hide it.
                        me.val(truncatedText).css('z-index', '1').after(popup).blur();
                        popup.fadeIn(opt.fadeinTime, function()
                        {
                            me.focus();
                            $(this).fadeOut(opt.fadeoutTime, function()
                            {
                                $(this).remove();
                            });
                        });
                    }
                };
            }
        });
    };
})(jQuery);

Add this in a js file and include this in the page where you require it.

Now to use it, we will write:

JavaScript
$('#txtComment').truncateLength({ maxLength: 10 });

Sample HTML Page's Content:

HTML
<head>
    <script src="js/jquery-1.3.2.js"></script>
    <script src="js/TruncateLength.js"></script>
    <script type="text/javascript">
        $(function () {
            $('#txtComment').truncateLength({ maxLength: 10 });
        });
    </script>
</head>
<body>
    <textarea id="txtComment"></textarea>
</body>

Live Demo

Points of Interest

It is very easy to create such a plugin but is very usable.
This plugin had helped me a lot and I know it will help you too.

History

  • Version #1: Created

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)