Erv Walter
Erv Walter

Reputation: 13788

What is the best JavaScript solution to limit the length of a textarea?

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.

Upvotes: 7

Views: 1003

Answers (5)

Seb
Seb

Reputation: 25157

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;
  }
});

Upvotes: 1

Josh Stodola
Josh Stodola

Reputation: 82523

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);

Upvotes: 1

Ilya Birman
Ilya Birman

Reputation: 10102

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 :-)

Upvotes: 5

Gavin Miller
Gavin Miller

Reputation: 43875

My non-technical $0.02

Do what SO does in their comment fields, provide feedback as to what the user's character length remaining is and allow them to go past the maximum, but not submit > 300 characters. Here's why:

  • Allowing users to go over the maximum number of characters allows them to complete an idea. They can then go back and edit that idea. There's nothing worse than being at the end of a sentence and being unable to complete it.
  • Providing feedback to character length keeps people from having to guess what their length is at.

    Upvotes: 23

  • Town
    Town

    Reputation: 14906

    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!

    Upvotes: 0

    Related Questions