0

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.

1

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

2 Comments

I'll also point out that these as they are don't cause infinite loops because setting value = value doesn't trigger change/input events, but if you're making other changes it might do, so be careful.
Nice answer! However, this erases text at the end rather than preventing input once max length is reached. Rather than tinker to make it work, I'll just go with maxlength. Who needs Opera and IE9 support anyway? :P

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.