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
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.
You should follow me on Twitter here I'll tweet about JavaScript, HTML 5 and other such gems (amongst usual tweet-splurges)
Superb.
copy/paste and limitation don't work
@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.
Remy: You are my jQuery idol!
Great stuff Remy - perfect timing for me too! Thanks.
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.
@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!)
@Remy: Thanks! Now it works like a Charm
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.
The plug-in automatically adds the needed spans and that as well.
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.
@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
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'),
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!
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.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!
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'),
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
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.
Actually Enter does count as 2 for IE but not for Firefox.
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