﻿

$(document).ready(function () {
    AttachEvents();
});

function AttachEvents() {
    $('textarea[MyMaxLength]').on("keypress", function (event) {
        return checkMaxLength(event, this);
    });

    $('textarea[MyMaxLength]').on("blur", function () {
        trimToMaxLength(this);
    });
}

function trimToMaxLength(el) {
    if (el.value.length > (el.getAttribute("MyMaxLength") - el.value.count('\n'))) {
        el.value = el.value.substring(0, el.getAttribute("MyMaxLength") - el.value.count('\n'));
    }
}

function checkMaxLength(e, el) {
    switch (e.keyCode) {
        case 37: // left
            return true;
        case 38: // up
            return true;
        case 39: // right
            return true;
        case 40: // down
            return true;
        case 8: // backspace
            return true;
        case 46: // delete
            return true;
        case 27: // escape
            return true;
        case 9: // tab
            return true;
    }
    return (el.value.length < (el.getAttribute("MyMaxLength") - el.value.count('\n')));
}