Frage

What is a cross-browser way to set the maximum number of characters in a textarea, using plain Javascript? maxlength does not work for textareas on Opera and IE9 and below (though it works on all major browsers for inputs).

Once the character limit is reached, the textarea should not allow more characters to be entered. Text pasted either with Ctrl+V or the right-click context menu should be cut off at the character limit. This means a solution that uses only onkey___ events is not sufficient.

War es hilfreich?

Lösung

Generate functions that will either truncate the value or prevent the Event under your conditions, and then add them as several different listeners for all the events you're interested in.

function snip(len) {
    return function (e) {e.target.value = e.target.value.slice(0, len);};
}
function prevent(len) {
    return function () {
        if (e.target.value.length >= len) {
            e.preventDefault();
            return false;
        }
    };
}

var len = 5; // choose your length however you want

var textarea = document.getElementById('texta'), // get the node
    trunc = snip(len),
    prev1 = prevent(len),
    prev2 = prevent(len - 1);

textarea.addEventListener('change'  , trunc, true);
textarea.addEventListener('input'   , trunc, true);
textarea.addEventListener('keydown' , prev2, true);
textarea.addEventListener('keypress', prev2, true);
textarea.addEventListener('keyup'   , prev1, true);
textarea.addEventListener('paste'   , trunc, true);

The events may need to be attached differently in IE

DEMO

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top