Click here to Skip to main content
15,891,184 members
Articles / Programming Languages / Javascript
Tip/Trick

Plugin for Textarea's MaxLength Validation

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
14 Jan 2014CPOL 8.5K   2  
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)


Written By
Software Developer
India India
Movie, music, social media, outdoors, family and good company; these are a few of my favorite things. Finding new ways to do things always excites me.

Currently I am working with some amazing persons at United HealthGroup, Hyderabad.

For me making websites is interesting than than using it. That's what creativity means to me.

Thanks for getting to know me, I would love to know you.

Comments and Discussions

 
-- There are no messages in this forum --