leodutra
8/2/2013 - 6:56 PM

Limits <textarea> length (`maxlength`). Uses data-maxlength and data-remaininglength to store data.

Limits

function limitTextAreaLength(selector, size) {
    var $ = jQuery;
    $(selector).each(function () {

        var self = $(this);
        self.attr('maxlength', size);
        self.data('maxlength', size);
        self.bind("keypress cut copy paste", function (event) {

            var textArea = $(this);

            setTimeout(function () {
                if (textArea.val().length > size) {
                    textArea.val(textArea.val().substr(0, size));
                }
                textArea.data('remaininglength', size - textArea.val().length)
                textArea = event = null;
            }, 100);
        });
    })
}