jQuery: limiting the number of characters inserted in a textarea

Limiting the number of characters inserted in a textarea element is a simple task with jQuery. All we have to do is to bind an action to the keypress and keyup events.

We can define a plugin that accepts two options: the former is the maximum number of characters allowed and the latter is an HTML element used as a counter:

(function($) {
    $.fn.limiter = function(options) {

        var that = this;
        options = $.extend({
            limit: 100,
            counter: $('#counter')
        }, options);

        var count = function(value, e) {

            var total = options.limit - value.length;

            if (total >= 0) {
                options.counter.text(total);
            } else {

                if (e.type == 'keypress') {

                    e.preventDefault();


                }
            }


        };

        return that.each(function() {

            $(that).on('keypress keyup', function(evt) {

                count($(that).val(), evt);

            });

        });

    };
})(jQuery);

$('#editor').limiter();​

The private count() method accepts two parameters. The first one is the value of the value property of our element and the second one is the event object. We can use this object to prevent a user from typing additional characters when the limit is exceeded. If the number has reached 0, we check the type property of the event object and we cancel its default action.

You can see the demo on this page.

Back to top