Monday, July 28, 2008

limiting characters in an html textarea

Here is a way to limit the amount of text entered into a textarea.  Note, this works in both IE and FireFox.  Also, this only limits characters entered via keystrokes and does not work for copy/paste.

/* -------------------------------------------------------------------------
limits the amount of text that can be typed into a textarea
example usage: <textarea onkeypress="return limitText(event, this, 40);">
--------------------------------------------------------------------------*/
limitText : function(event, textArea, maxChars) {
    var result = true;

    if (textArea.value.length >= maxChars) {

        if (textArea.createTextRange) {
            var range = document.selection.createRange().duplicate();
            result = range.text.length > 0;
        } else {
            result = event.keyCode in { // always let these keys through
                37 : "left",
                39 : "right",
                38 : "up",
                40 : "down",
                33 : "pageUp",
                34 : "pageDown",
                46 : "del",
                36 : "home",
                35 : "end",
                27 : "esc",
                8 : "back"
            };
        }
    }

    return result
} // limitText()



No comments: