Check out my latest project: Full Frontal JavaScript Conference

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.

42 Responses to “maxlength plugin”

  1. Hello Remy,
    When i put your textarea code on a form it works great, but when I add it to my WordPress it is conflicting with another plugin and I am getting this error in Firebug.
    $ is not a function
    $('textarea.limited').maxlength({
    Not sure if you have heard or experienced this issue or if maybe you had any ideas? I would post the link, but my boss wouldn't be too happy if I did that...
    you can email me at kyleaknight [at] gmail.com if you would like a link.

    Thanks!

  2. @KyleKnight - try changing the code to jQuery('textarea.limit').maxlength() (i.e. you may have prototype on the page that has control of the $ function).

  3. Great plugin, thanks.

    I'm with Anders, please allow us to specify maxlength as an option, maybe even allow maxlength (or limit) param to be a function?

    function myOwnLimitFunction(element, options) {
    return (options.useInput ? $(element.form).find('input[id=maxlength']).val() : $(element).attr('maxlength'))
    }
    Like this: ('#selector').maxlength({limit: myOwnLimitFunction})

    This will allow to extend your great plugin to suit almost every need.

  4. Hi Remy,

    It's have been a while. I've develop a similar plugin some days ago with a progress bar indicator also. I have pending a post about it, but I have develop some other things and use it as an example (with your tagSuggestion plugin also).

    What do you think about it?
    http://weblogs.manas.com.ar/bcardiff/2008/12/declarative-jquery-with-microsoft-ajax/

    Cheers

  5. Hi,

    I wrote some custom code for work, and wanted to translate that to a jquery plugin, but of course someone else had done it already =)
    nice work. i like the word limit functionality!

    couple of points though:

    * truncating bad for usability? if the user has typed something, and then paste in the middle, it will truncate out the last characters (which is what they typed). Not all browsers have undo on the textarea (e.g. safari, google chrome) so they have lost their work.

    * IE, FF3, and newer Webkit supports onpaste on the textarea. this means you can also handle mouse paste and menu pastes on these browsers too.

    * what about also detecting when there is a selection on the textarea, to allow them to enter text.

  6. This is exactly the sort of thing to add to the ole' toolbox. Thanks!

  7. [...] 37. MaxlengthIt’s a fairly common design practice to limit the number of characters a user can input in a field while giving feedback on how many spaces are left. This plug-in automates that task. [...]

  8. Awesome plugin!! A great feature would be to only show the counter counting for the last N characters.... The user doesn't need to be concerned or distracted by a countdown if he/she is not yet close to approaching the limit, and might never exceed the limit.

  9. Hello,

    Excellent plugin, just one question, could it be possible to use it for the "reverse" of what it was designed for ?
    I explain, in my case don't want to impose a maximum character's length but a minimal characters length.

    Bye,
    Hervé

  10. @Hervé - Use something like LiveValidation instead…

    as such:

    
    <input type="text" name="title" id="title"  />
    
    <script type="text/javascript">
    var title = new LiveValidation( 'title', { validMessage: "The computer says YES", wait: 100 } );
    title.add( Validate.Length, { minimum: 4, maximum: 30 } );
    </script>
    
  11. Thank you for the tip Philip !

  12. hi remy! is there a way to integrate this script with wordpress?

    not to use it on a comments form, but to use it in the "core", to count characters while i'm writing a post (or to limit the amount of characters a post may have)

    thank you!

  13. Hey, great plugin!

    I have a little favor to ask though, because a beginner as I am in JQuery I can't figure out a solution:
    In FF a return is counted as one character and in IE as two characters. I need to make a return count as 2 characters in FF too because my application lies on top of an Oracle DB (which in my case) which converts a return into two characters too.

    If it's not too much trouble, could you show me how to adapt your plugin a bit to make it work better for me?

    Thanks in advance!

    Kind regards

  14. Sorry for the question, but where and how can I install this plugin?
    Thanks.

  15. The copy/paste can't work when characters reach the maxlength. Can you fix this?
    I mean copy the text from textarea which remain characters is zero to notepad.
    Thanks! :^)

  16. Hi~ I think I already fixed the copy/paste problem. And I add some advance limit check rule, maybe you can take a look.
    Here is the modified code:
    http://fstoke.net/jquery.maxlength_mod.js

    the main modification:
    1. if textarea got selected text, then just pass when doing limitCheck
    2. if ctrl or alt key is still pressed, then just pass it too

    Thanks a lot for your plugin! :^)

    The code I add:

    
    $.fn.maxlength = function (settings) {
      var ctrlPressed = false;
      var altPressed = false;
      ...
    
        function limitCheck(event) {
          ...
          // if got selected text, then just pass it
          var sl = (this.value).substring(this.selectionStart, this.selectionEnd);
          if( sl != '' )
            return;
    
          // if ctrl or alt key is still pressed, then jsut pass it
          if( ctrlPressed || altPressed )
            return; 
    
          switch (code) {
            case 17: // ctrl
              ctrlPressed = true;
              return;
            case 18: // alt
              altPressed = true;
              return;
            ...
        }
    
        ...
    
        $field.keyup(updateCount).change(updateCount);
        if (settings.hardLimit) {
          $field.keydown(limitCheck);
          $field.keyup(function (event) {
            if( event.which == 17 ) ctrlPressed = false;
            if( event.which == 18 ) altPressed = false;
          });
        }
    
    ...
    
  17. like darrell and diana, can someone post a fix for firefox to counter enter as 2 characters?

    GREAT PLUGIN! thanks!

  18. Eric, Darrell, Diana -

    I added an optional setting ("windowsLineBreaks") to the plugin to address what you are referring to. If you enable the setting, it counts Enter from Firefox, Safari, etc as two characters. Some browsers (IE) actually DO input the two characters, so it's smart enough to not double-count in those cases.

    Hopefully Remy will fold this addition into his post, but for now you can see my updated version of the plugin here:

    http://code.smashd.net/js/maxlength/

    Remy, many thanks for the initial code! If you like my addition feel free to update your post accordingly. Just let me know so I can update any references to it on my site. Thanks!

  19. Hi~~
    The plugin I modified is moved to the following url to fix the isssue:
    [The copy/paste can't work when characters reach the maxlength]

    http://fstoke.net/jquery/jquery.maxlength_mod.js

  20. Hey guys,

    I'm developing a commenting system for a site and am using this great plugin to limit the comments to a specific length.

    It works great for textareas that are loaded with the page, but it stops working for textareas that are loaded via ajax (for example when replying to a comment, the reply form is loaded from the backend via an ajax call)

    I have a feeling this has something to do with binding, but I cannot figure it out how to make it work.

    Any ideas?

    Thanks,
    Konstantin

Leave a Reply
Not required

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