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.

41 Responses to “maxlength plugin”

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

Leave a Reply
Not required

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