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.
The plugin simply reports back the number of characters left the user has, with a few extra bells and whistles.
This demo shows off two example, one limiting on characters and one limiting on words.
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:
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).
- 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.