06th May 2008

Setting a Character Limit for TextArea with jQuery

So today I was asked to impose a character limit on a messaging system I have been working on. The message in question is input into a textarea in a form. So I vaguely remember something about a max character property and proceed to do a google search for character limit textarea. Well as it turns out, the character limit I was thinking of only applies to inputs of type text. What I found in my search results were various permutation of using JavaScript to impose a limit. Since I am now a big fan of jQuery, I decided to implement it using that.

Here is what I ended up doing.

  1. Assign a common class to the message text areas. Using a class as opposed to an ID allows us to apply this to multiple text areas on the same page, should the need arise.
  2. In the script file for the page bind a function to check the length of the text in the text area as follows:
    $(document).ready(initPage);
    function initPage(){
    $('.myTextAreaClass').keypress(limitMessageLength)
    }
  3. Create a function to limit the number of characters:
    function limitMessageLength(){
    var text = $(this).val();
    if (text.length > 100) {
    $(this).val(text.substr(0, 100));
    }
    }

Now any page that includes this script file and has forms with text areas with that class, will trigger the limiting function.

I have noticed some weirdness where when you reach the character limit, the last character changes to the last character you typed, but over all, seems to get the job done.

Comments are closed.