Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 592
Erv Walter Avatar asked Mar 17 '09 14:03

Erv Walter


2 Answers

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.
  • like image 123
    Gavin Miller Avatar answered Sep 19 '22 07:09

    Gavin Miller


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

    like image 45
    Ilya Birman Avatar answered Sep 21 '22 07:09

    Ilya Birman