SimpleMaxChars Plugin for jQuery

Web Design & Development

My SimpleMaxChars jQuery plugin adds a message displaying the number of characters remaining in an <input> or <textarea>. I needed a fairly basic solution quickly and most of the existing plugins that offer similar functionality were too big, too small, buggy, or didn’t meet my specific needs. If this looks like it will work for you, feel free to use it!

Highlights

  • Less than 2KB minified
  • Adds a warning class to the message when the character limit has nearly been reached (useful for changing the color of the message via CSS)
  • Uses .prop() and .attr() correctly (.attr() is often used incorrectly for setting/getting DOM properties)
  • Multiple instances can be used on the same page
    • Can be used on individual form elements with unique options for each element
    • Can be used on multiple form elements with the same options
  • Uses the maxLength property of the element, but can be overriden with a custom maxLength
  • Has built-in options for basic customization
  • Remaining character message can be customized via $.fn.SimpleMaxChars.message = function(){ yourCustomFunction });
  • Tested with jQuery 1.6.2+, IE7+, Chrome 17, Firefox 8

Using the Plugin

Download the plugin from GitHub. Select the form element(s) you want to use via a jQuery selector, then call the plugin with any options you want to use. I wrote this initially to use on SharePoint forms (in MOSS 2007), so my implementation looks like this:

// Display remaining characters in Title field
$( "input[title='Title']" ).SimpleMaxChars({
	lineBreak : true,
	warningClass : "ms-formvalidation"
});

By using “ms-formvalidation” as the warningClass option along with lineBreak : true, the remaining characters message looks just like a standard SharePoint description below the field. When the character warning limit is reached, the message color changes and resembles a standard validation error message. This presents the user with a consistent UX. Also, because SharePoint outputs a maxlength attribute on single line of text fields, the plugin automagically uses that value without the need to specify it in the plugin options.

Screenshot of SimpleMaxChars message
SimpleMaxChars displays the number of remaining characters for an input or textarea.
Screenshot of SimpleMaxChars warning message
When a certain threshold has been reached, an additional class is added to the message. In this screenshot, the "ms-formvalidation" class has been added by the plugin to make the text appear red, just like other SharePoint validation messages.

Read the full documentation with all available options on GitHub.

Suggestions

This is the first time I’ve created a GitHub repository, so I’m still learning the ins and outs of using it. However, if you have any suggestions or ideas for this plugin, feel free to fork the repository and submit a pull request with your changes, or leave a comment!