Check out my latest project: Code Dumper

maxlength plugin

It's a fairly common design pattern to want to limit the number of characters the user can input in a field whilst giving feedback to the user on how much they have left.

So I've built a little jQuery plugin to do the work for me.

Maxlength Plugin

The plugin simply reports back the number of characters left the user has, with a few extra bells and whistles.

Download the maxlength jQuery plugin

Demonstration

View the maxlength demo

This demo shows off two example, one limiting on characters and one limiting on words.

Example Code

<form action="/comment">
  <p>Characters left: <span class="charsLeft">10</span></p>
  <textarea maxlength="10" class="limited"></textarea>
</form>
<script type="text/javascript">
  $('textarea.limited').maxlength({
    'feedback' : '.charsLeft'
  });
</script>

The default version of the maxlength plugin reads the maxlength attribute from the text element. However, since this isn't a valid HTML attribute if added to a textarea you can configure the plugin to read the value from a hidden input:

<form action="/comment">
  <p>Characters left: <span class="charsLeft">10</span></p>
  <textarea class="limited"></textarea>
  <input type="hidden" name="maxlength" value="10" />
</form>
<script type="text/javascript">
  $('textarea.limited').maxlength({
    'feedback' : '.charsLeft',
    'useInput' : true
  });
</script>

The plugin can be applied to input elements, but if you want to limit by words, rather than characters, you need to put the maxlength as a hidden input (otherwise the browser will use it's default behaviour to limit the user's input).

Plugin Options

  • feedback - the selector for the element that gives the user feedback. Note that this will be relative to the form the plugin is run against.
  • hardLimit - whether to stop the user being able to keep adding characters. Defaults to true.
  • useInput - whether to look for a hidden input named 'maxlength' instead of the maxlength attribute. Defaults to false.
  • words - limit by characters or words, set this to true to limit by words. Defaults to false.

15 Responses to “maxlength plugin”

  1. Superb.

  2. copy/paste and limitation don't work

  3. @Marius - great feedback. Paste limitation now implemented (v1.1). There's obviously going to be a brief flicker as the text goes in, then it's truncated.

    This feature works both with character limits and word limits.

  4. Remy: You are my jQuery idol!

  5. Great stuff Remy - perfect timing for me too! Thanks.

  6. When you're reached the max limit of the box, ctrl-a, delete, home and end do not work. Those are keyCodes: 17 + 65, 46, 36, 35.

  7. @Paul - cheers.

    I've updated maxlength to include Paul's extra keys, code tidy from Ariel Flesler and a fix to ensure pasting over the limit, maintains the white space structure (check out the rather cool split on line 75!)

  8. @Remy: Thanks! Now it works like a Charm :)

  9. Nice!

    I've created a similar one that runs on all inputs with a class of ^="maxlength-XXX" where XXX would be an int saying how many characters the input is limited to.

    
    var maxLengthInputs = function() {
      $('*[class^="maxlength"]').each(function() {
        var t = $(this),
              maxLength = t.attr('class').substring(10),
               left = maxLength - t.val().length;
    
        var charLeft = $('' +left +' characters left').insertAfter(t);
    
        t.keyup(function() {
          if(t.val().length > maxLength) {
            t.val(t.val().substring(0, maxLength));
          }
          var left = maxLength - t.val().length;
    
          charLeft.text(left +' characters left');
        });
      });
    };
    

    The plug-in automatically adds the needed spans and that as well.

  10. Nice plugin! I noticed on the Word limit textarea in your examples you can type in 10 words but then the last word is allowed to be any number of characters long. Is this a feature or a bug? I am on FF3 on OS X.

    I wrote a similar piece of code which looks in the title attribute of the textarea for the maxlength and automatically adds a div containing the number of characters remaining after the textarea. I also add a class which colors the text red when the limit is reached/exceeded. I am not quite up to turning it into a plugin but I only need to add 7 lines of script to my form pages and it handles all textareas with a title attribute.

  11. @David - no that's not a bug. If you are limiting by number of words, then the words can be any length, including the last one.

    I've tried to make the plugin enhance the page in a way the degrades well. It's because of this in particular that I don't create the counter dynamically. If JS is turned off, the user still gets to know the limit - though there's no count down - they will receive (I should expect) a server side message notifying their content is too long. With JS - it's added functionality :-)

  12. Hi. Lovely script. Just wanted to say that there really should be an option for just passing on the max length on function call instead of having it somewhere in the HTML. When using it in my own system, I made a tiny hack to add the option 'length'.

    edit: The hack was to change this code (around line 34):
    limit = settings.useInput ? $form.find('input[name=maxlength]').val() : $field.attr('maxlength'),

    to this:
    limit = settings.length ? settings.length : settings.useInput ? $form.find('input[name=maxlength]').val() : $field.attr('maxlength'),

  13. Hey, thanks for this. Is there any way we can use this on a page with multiple controls (all have the same word limit though)? Sorry if this sounds naive..im still very much a beginner in jQuery!

  14. Think I figured it out.. Basically, replaced line $charsLeft = $form.find(settings.feedback); with
    $charsLeft = $field.parent().find("span[class=wordsLeft]"); . Hence, instead of specifying a particular span tag, it automatically finds corresponding sibling span tag and updates with words/characters left.

  15. Word count doesn't seem to work in IE7.
    field.value.split(/(s+)/, (limit*2)-1).join('')
    In firefox, the split keeps the whitespace in array, in IE7 it looses the whitespace.
    Is there a fix for this? Thanks!

Leave a Reply
Not required

CODE: Please escape code and wrap in <pre><code>, doing so will automatically syntax highlight