views:

489

answers:

5

Is there a canonical solution for limiting the number of characters that someone can enter into a textarea?

I have server side validation of course, but would like to improve the user experience by adding client side code to simulate the experience you get with maxlength on an input[type="text"] so that users never see the "your input is too long" error message if they have javascript enabled.

+1  A: 

Attach an onchange event to the textarea. There you can check if the value's larger than the appropriate or not. Example with jQuery:

$("#textarea-id").change(function (){
  var text = $(this).val();
  if( text.length > MAX ){
    return false;
  }
});
Seb
Onchange will only fire after you leave (blur) the textarea.
Ilya Birman
That aborts the entire change even if it is 1 character too long?
Erv Walter
You can't abort a change event, anyway.
Josh Stodola
ah the obligatory jquery response
A: 

I've done it like this in the past:

<textarea onkeyup="checkLength(this);"></textarea>

Then implement this function:

function checkLength(control) {
            if (control.value.length > 5) {
                control.value = control.value.substr(0, 5);
            }
        }

It's a pretty basic example fixing the length to 5, but hopefully gives you the idea!

Town
I won't give you a -1, but I don't think "keyup" is sufficient. You can paste text in without a keyboard event, for example.
Jason Cohen
It's better to use onchange than onkeyup because the change event will capture things like pasted text and keys held down. Think of it this way, you're interested in the data, not what how the user is manipulating it
annakata
Good point - it'll still work with keyup for ctrl-V but not for right-click and Paste. onchange isn't nice either though as it only fires when the user exits the box, meaning they'd end up typing loads only to see it cleared back to 5 characters (or whatever the limit is).
Town
+19  A: 
Gavin Miller
It was a hard decision to give you a +1 since I have my own answer here :-) But I find your reasons quite valueable for the topic.
Ilya Birman
+5  A: 

I would do it this way:

$ ('#textarea-id').bind (
  'change input keyup keydown keypress mouseup mousedown cut copy paste',
  function () { return ($(this).val().length <= maxlength) }
)

So many bingings just to be completely sure :-)

Ilya Birman
Not working in Firefox.
Cesar
Isn't working. When char limit is reached it is not possible to change it anymore. Not even delete.
Ismael
+1  A: 

This will do it...

function textareaMaxLen(event) {
  var max = parseInt(this.attr("maxlength"), 10);
  if(this.value.length >= max)
    this.value = this.value.substr(0, max);
}

$("textarea").keyup(textareaMaxLen).blur(textareaMaxLen);
Josh Stodola