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.
UK EVENTAttend ffconf.org 2024
The conference for people who are passionate about the web. 8 amazing speakers with real human interaction and content you can't just read in a blog post or watch on a tiktok!
£249+VAT - reserve your place today
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.