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.

49 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!

  16. any thoughts on supporting the metadata plugin? not sure if I did it correctly, but I made the following changes to utilize the metadata plugin:

    1. moved the length function within the “return this.each(function() { . . . })” block

    2. added this line within the block:
    var opts = $.metadata ? $.extend( {}, settings, $(this).metadata() ) : settings;

    3. changed all references to the “settings” variable within the block to “opts”

    4. changed the assignment of the limit variable
    limit = settings.useInput ? $form.find(‘input[name=maxlength]‘).val() : opts.maxlength ? opts.maxlength : $field.attr(‘maxlength’),

  17. hello,

    thanks for this script, one question, how to i prevent someone for keeping on hitting enter. For example my char limit is 200. but the user can press enter 200x. Is there a way to make a line limit as well? so they could do it say 5x.

    Thanks,
    Brandon

  18. I think you need to count 2 for the Enter key. When processing the form on the server using php or java the Enter is actually CR+LF – 2 characters.

  19. Actually Enter does count as 2 for IE but not for Firefox.

  20. When you’ve reached the limit in the first example, you can still enter the letter ‘a’, including holding it down to enter multiple. As soon as you let go, it truncates it. Any other key I pressed simply did not get entered (the expected behavior).

    Firefox 2.0.0.17, Win XP

  21. 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!

  22. @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).

  23. 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.

  24. 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

  25. 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.

  26. This is exactly the sort of thing to add to the ole’ toolbox. Thanks!

  27. [...] 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. [...]

  28. 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.

  29. 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é

  30. @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>
    
  31. Thank you for the tip Philip !

  32. 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!

  33. 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

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

  35. 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! :^)

  36. 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;
          });
        }
    
    ...
    
  37. like darrell and diana, can someone post a fix for firefox to counter enter as 2 characters?

    GREAT PLUGIN! thanks!

  38. 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!

  39. 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

  40. 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

  41. Hi,

    I’d love to use this plugin, but I can’t seem to get it to work on more that one text area in a single form. Is it possible to have multiple text areas with various word limits in a single form? If so, how do I set this up?

    This is exactly what I was looking for, but I’ve got a form with 8 textarea controls that need word limits.

    Thanks for a great plugin and any help,

    Tony

  42. Nice, but I can’t turn off the hard limit somehow… isn’t this correct?


    'feedback' : '.charsLeft',
    'hardLimit' : false

  43. I found “a”s were still showing up then being cut off due to Ctrl-A fix so i changed the switch to this:

                    case 46:
                        return;
                    case 65: // for Ctrl-A
                    case 67: // for Ctrl-C
                        if(event.ctrlKey) {
                            return;
                        }
                        else {
                            return settings.words && code != 32 && code != 13 && len == limit;
                        }
                    default:
                        return settings.words && code != 32 && code != 13 && len == limit;
    

    Don’t particularly like the dup code, but it seems to work.

  44. Yay, you win the ‘best implementation’ award – nice and clean and simple. My question is – is there an easy way to introduce a ‘soft limit’ prior to the hard limit, where you could have some CSS help the user see the approaching end – eg word/char count/text/bg (pick one) changes color? I would define this as ‘targetLength’ and then ‘maxLength’.
    Two advantages – people can write _then_ edit, and feedback is more obvious.

    I’ll be using this as it is, but would love it if you could tell me how to add those two little bells :)

    Adrian

  45. Word count is not wprking in CHROME.. :(

  46. Edmark is right – word count doesn’t seem to like Chrome or Firefox 4 at all… (which is a shame, because it’s such a rockin’ little plugin!)

  47. I’m in FF5 and it seems to count the words correctly, but doesn’t block based on words properly. it’s blocking by # of characters. and it seems as though Remy has given up on this plugin – understandably, it’s been years.

    let’s fix it!

  48. G’day, a simple fix for FF4+ and Chrome is to replace line #38 with the following, which allows you to specify the maxlength in the settings:

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

    e.g.
    $("#example").maxlength({ maxlength: 100, words: true });

  49. I know it has been years but I was having the same problem as tonyg above. The plugin wouldn’t work for me if there were multiple textareas on a form. To get around it I set the span to use an id instead of class. I also had to change the starting value if there was already text in the box when the view loads. Here is my code to set all the textareas on the page:

    
    function setTextAreaLimit() {
        $("textarea").each(function () {
            var currentLength = 4000 - $(this).val().length;
            var id = $(this).attr("id");
            $(this).attr("maxlength", "4000");
            $(this).after("Characters remaining: "+currentLength+"");
            $(this).maxlength({
               'feedback': '#charsLeft' + id
            });
            var span = $("#charsLeft" + id);
            span.text(currentLength);
        });
    }
    
    
Leave a Reply
Not required

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