Easily add a max character limit on any HTML input or textarea form field. Also dynamically updates status message countdown to user, eg, “10 remaining” as they type. Has several options. Message is customizable. Correctly handles user events, even paste via right click menu.
Update: version 0.3.0 is out
This post is about the 0.1.0 version. The newest version is now 0.3.0. To see the new version and keep up with future updates, see the main maxChar page.
Features for version 0.1.0 (deprecated, see Update above)
- No JavaScript in HTML tags
- Drop dead simple with sensible defaults or completely customizable with overrides
- Have plural and singular forms of message
- Easily work with multiple target fields, as many as I want
- Properly handle user pasting text via right click menu
- Be able to properly handle updating message
Basic example .. doesn’t get any easier than this
The most common use case is to add the maxChar functionality to a textarea, eg, in a comment form. Just load jquery, load the plugin, and initialize it on the target form element while passing the character limit you want to enforce.
Instructions
- Add links to jQuery and the maxChar plugin in your HTML head section.
- In your HTML head section, initialize the plugin in your jQuery ready block.
1
2
3
4
5
6<script type="text/javascript">
$(document).ready(function(){
// Pass HTML element id and character limit.
$('#message').maxChar(50);
});
</script> - In your HTML, just make sure your input or textarea element has the id you passed to maxChar above.
NOTE: although below the only element you create is the textarea element, the maxChar plugin dynamically creates and adds a span element after the textarea element. This dynamically created span element is the container for the updated status message, eg, “N remaining.”
Advanced Examples: You want options, you got options
I added the options that made sense to me. Check ‘em out.
Option: indicator
The indicator is the HTML element that displays the status message, such as “10 remaining.” By default, maxChar dynamically creates a span element with an id=”indicator”, then adds it in the DOM after the target element, in our previous example, after the textarea.
Sometimes, though, you will want to override the default indicator HTML element and specify your own. Just pass the indicator id as a parameter and maxChar will not dynamicaly create and insert a span element; it will instead update your specified HTML element with the status message.
1 2 3 4 5 6 | <script type="text/javascript"> $(document).ready(function(){ // Pass HTML element id and character limit. $('#message').maxChar(50, {indicator:'custom_element'}); }); </script> |
And in your HTML, add the custom element wherever you want it in your design.
Setting up multiple instances
Using the indicator option is usually mandatory when using maxChar with multiple form fields, since you normally want each field will need it’s own indicator. (If you do not specify multiple indicators, all targeted fields with share the single indicator; this would be an interesting design but probably a little confusing.)
1 2 3 4 5 6 7 | <script type="text/javascript"> $(document).ready(function(){ // Pass HTML element id and character limit. $('#name').maxChar(10, {indicator:'nameIndicator'}); $('#message').maxChar(50, {indicator:'messageIndicator'}); }); </script> |
And in your HTML, specify your HTML input and textarea and the matching span elements for their indicators.
1 2 |
Options: singularMessage and pluralMessage
You can also change the indicator’s status message. By default it says “N remaining” but you can change the text after the number (N) to whatever you want. You can also create singular and plural versions, eg, “2 characters remaining” and “1 character remaining.”
1 2 3 4 5 6 | <script type="text/javascript"> $(document).ready(function(){ // Pass HTML element id and character limit. $('#message').maxChar(50, {singularMessage:' character remaining',pluralMessage:' characters remaining'}); }); </script> |
Option: spaceBeforeMessage
In addition to changing the status message itself, you can also specify the spacing in front of the message. This option is handy if the status message should, or should not, have a space between it and the textarea or input element. The default is one space character. In the following example I remove any space by setting to an empty string.
1 2 3 4 5 6 | <script type="text/javascript"> $(document).ready(function(){ // The default space is one space character ' '. Use the spaceBeforeMessage option to change it. $('#message').maxChar(50, {spaceBeforeMessage:''}); }); </script> |
Option: rate
The interval at which maxChar runs is configurable. The default is 200 milliseconds. Sometimes you might want to tweak this rate for your own reasons. I found myself setting to different values to get the exact rate I felt was user-friendly. Since you might have your own preference, I made it an option.
1 2 3 4 5 6 | <script type="text/javascript"> $(document).ready(function(){ // The default rate is 200 milliseconds. Use the rate option to set it whatever you wish. $('#message').maxChar(50, {rate:500}); }); </script> |

#1 by Keegan Watkins on August 4th, 2009
Quote
that’s pretty sweet, mitch! i was wondering if you considered supporting a byte-length as well as the character count? seems character counts are often tied to database field limits, and dual and triple-byte characters can jack with plugins like this if they are being used to enforce those limits. should be pretty easy to match against entire languages using unicode regex classes… just a thought. great work man!
#2 by Mitch Wilson on August 4th, 2009
Quote
Hey, Keegan! Thanks for the tip. I’d like to see the bug in action. Do you have an example? I know there are issues when escaping asian characters. I’m not escapging characters, though. Trimming the characters depends only on the JavaScript String.length property and the slice method.
#3 by Keegan Watkins on August 5th, 2009
Quote
hey mitch! so, i may not have been clear in my earlier post: what i was driving at was that this plugin might serve more use cases by adding support for validating a particular unicode length. that all depends on the use YOU have for it, but it has been my experience that the need to enforce a character limit is often driven by database limitations. for example, if a particular field is limited to one hundred bytes, you could use maxChar to enforce that, as long as you can be sure that each character only takes one byte of space. as non-western characters are often dual or triple-byte, to serve that case i think it’d be cool to validate against actual byte-length as opposed to character count. i’ve whipped up a (very) rough prototype, but it hasn’t been tested thoroughly and could probably be optimized. the basic idea i had was this:
// Anonymous function to create the closure.
(function($) {
// Expose as jQuery plugin.
$.fn.validateuniLength = function(limit) {
return validateuniLength(this[0], limit);
}
// Raw JS, could be implemented in other frameworks
function validateuniLength(el, limit) {
// Account for elements,
// which do not have a “value” property
var input = el.value || el.innerText || el.text;
var len = input.length;
// Includes both eastern and western foreign chars (2-bytes)
var rgxExclusion = /[\u0080-\uFFFF]/g;
// Some western/all eastern foreign chars (potentially 3-bytes)
var easternExclusion = /[\u0100-\uFFFF]/g;
var matches = input.match(rgxExclusion);
var uniLen = 0;
// Foreign chars present
if (matches !== null) {
var eastern = input.match(easternExclusion);
var easternLen = 0;
// Eastern chars present
if (eastern !== null) {
easternLen = eastern.length;
}
// Assume 3 – most will be 2 but some kanjii are 3-bytes
uniLen = (easternLen * 3) + ((matches.length – easternLen) * 2);
len = len – matches.length + uniLen;
}
return len > limit ? false : true;
}
})(jQuery); // Pass jQuery, allows aliasing to “$” without impacting other libs
#4 by Keegan Watkins on August 5th, 2009
Quote
sorry for the janky formatting, it’s a short one though so should be pretty easy to see if you re-apply indentation. at any rate, usage would be as follows:
// Returns true if the value is under 100 bytes, false otherwise
$(”#mFormElement).validateuniLength(100)
#5 by Mitch Wilson on August 5th, 2009
Quote
Ah ok. So it’s really a database issue. I have worked a lot with Japanese, Korean and Chinese in the past in XML and HTML files. But I have not worked with storing Asian language content in databases. I can say this, though: the database needs to use the correct character set, just like a Web page needs to use the right character set to display the characters properly. If you have a database table using a non-Asian character set when storing data, then I believe you would have the issue you described.
Of course, the only way to know is to test it. The way to test it accurately would be to create a database using the correct character set, then start your development machine (windows) with the right locale setting so your machine is using the right character set, then create the Web page in your text editor (one that uses the right character set correctly) then test the page using Japanese text, then display the text back from the database.
Are you working with Asian text now? Could you do that?
#6 by poon fung on August 31st, 2009
Quote
This is very nice. Thank you!
PROBLEM. When a textarea is filled to maxlength, the vertical scroll bar refused to scroll down (I am using Windows XP). I have to backspace once to get scroll bar to work.
I think we can fix this by checking if keydown=scrollchar before checking for maxlength.
QUESTION: It is clever to use the timer initiate checking. This takes care of both keyboard input as well as cut-and-past. However, I run into a problem when I try to set a initial message (different from the count message) which will be erased once a user starts typing. Any suggestion on how that may be done?
#7 by poon fung on August 31st, 2009
Quote
PROBLEM 2: Just found and other problem. When there are both singular and plural messages, it displays plural message ‘0 characters left’ instead of ‘0 character left’.
#8 by poon fung on August 31st, 2009
Quote
OK.
Aftering checking out the code. I made the following change to fix two of the three issues I mentioned above.
1. Plural message problem
In function update(), change this:
if(remaining == 1) {
indicator.text(remaining + singularMessage);
} else {
indicator.text(remaining + pluralMessage);
}
to
if(remaining <= 1) {
indicator.text(remaining + singularMessage);
} else {
indicator.text(remaining + pluralMessage);
}
2. Setting an initial message that disappear when user start editing:
Add these lines after var pluralMessage = …
var beginLength=target.val().length;
var editStarted=false;
In update(), change first line to
var length = target.val().length;
if (!editStarted && beginLength == length)
{
return;
}
editStarted = true;
var remaining = limit – length;
A more elegant solution is to add another option to control an initial message is allowed.
OK. Aftering checking out the code. I made the following change to fix two of the three issues I mentioned above.
1. Plural message problem
In function update(), change this:
if(remaining == 1) {
indicator.text(remaining + singularMessage);
} else {
indicator.text(remaining + pluralMessage);
}
to
if(remaining <= 1) {
indicator.text(remaining + singularMessage);
} else {
indicator.text(remaining + pluralMessage);
}
2. Setting an initial message that disappear when user start editing:
Add these lines after var pluralMessage = …
var beginLength=target.val().length;
var editStarted=false;
In update(), change first line to
var length = target.val().length;
if (!editStarted && beginLength == length)
{
return;
}
editStarted = true;
var remaining = limit – length;
A more elegant solution is to add another option to control an initial message is allowed.
#9 by Mitch Wilson on September 16th, 2009
Quote
Hey Poon,
Thanks for the comments. I’ve been extremely busy with work and haven’t had a chance to blog lately. I will definitely look the issues and code examples you provided.
Thanks again!
#10 by Mitch Wilson on October 10th, 2009
Quote
Poon,
Here is an answer to each of your three questions/issues. I created a new version (0.2.0) that adds the support I think you requested. Let me know what you think. I hope it helps.
Keegan,
I have not been able to reproduce the issues you described. Maybe I misunderstood or you can provide the tests. Let’s have a beer and discuss!
New in 0.2.0
What I did not change
Poon, I agree that using the plural message for 0 remaining is weird. English grammar is weird sometimes. The code is correct as is: in English, it is grammatically correct to use the plural form for 0, for example, “0 characters remaining.”
Regarding the reported vertical scrollbar issue, I could not reproduce in IE8. Also, it should be noted that the behavior of a vertical scrollbar on a textarea varies from browser to browser and is a problem in general. I can’t find that my jquery.maxChar script has any affect on whether a vertical scrollbar appears correctly or not.
The solution for the issue in general, for both IE and Firefox, is to specify the rows attribute on the textarea element.
#11 by XZero on October 11th, 2009
Quote
Hello, greetings from Peru. Sombe could response me. I nee your help for this Jquery functiopn like Mr.’s Mitvh jquery.maxchars:
/*
function limitTextArea(target, indicator, chars, charsPerLine){
var max_chars = chars;
var max_chars_per_line = charsPerLine;
var num_lines = 5;
var remaining_chars = max_chars;
var remaining_chars_current_line = max_chars_per_line;
var total_chars = 0;
var current_line_chars = 0;
var current_line = 0;
var num_enters = 0;
var target = $(target);
//var current = $(”#current”);
var indicator = $(indicator);
var total = $(”#total”);
//current.text(”Current line: ” + current_line_chars);
indicator.text(”Remaining: ” + remaining_chars_current_line);
total.text(”Total: ” + total_chars);
target.focus();
target.keydown(function(e){
//if(e.which == 32 || (65 <= e.which && e.which <= 65 + 25) || (97 <= e.which && e.which = max_chars){
target.val(target.val().slice(0,max_chars + num_enters – 1));
total_chars = max_chars;
if(e.which == 8){
remaining_chars_current_line += 1;
current_line_chars -= 1;
total_chars -= 1;
if(total_chars < 0){
total_chars = 0;
num_enters = 0;
}
}
}
else{
if(e.which == 8){
remaining_chars_current_line += 1;
current_line_chars -= 1;
total_chars -= 1;
if(total_chars max_chars_per_line){
remaining_chars_current_line = max_chars_per_line;
current_line_chars = 0;
}
if(remaining_chars_current_line < 0){
target.val(target.val() + "\n");
remaining_chars_current_line = max_chars_per_line – 1;
current_line_chars = 0;
num_enters += 1;
}
}
//current.text("Current line: " + current_line_chars);
indicator.text("Remaining: " + remaining_chars_current_line);
total.text("Total: " + total_chars);
//}
});
}
$(document).ready(function(){
limitTextArea("#text","#remaining",30,3);
});
*/
Thx!
#12 by XZero on October 11th, 2009
Quote
Ops! My query is I could add maximum number of rows for my function, It has got maximum number of chars and mamimun number of chars per line.
Thx again!
#13 by XZero on October 11th, 2009
Quote
Here’s an update:
function limitTextArea(target, indicator, chars, charsPerLine){
var max_chars = chars;
var max_chars_per_line = charsPerLine;
var num_lines = 5;
var remaining_chars = max_chars;
var remaining_chars_current_line = max_chars_per_line;
var current_line_chars = 0;
var current_line = 0;
var num_enters = 0;
var target = $(target);
var indicator = $(indicator);
var total_chars = target.val().length;
indicator.text(”(Caracteres restantes: ” + (max_chars – total_chars) + “)”);
target.focus();
target.keydown(function(e){
//if(e.which == 32 || (65 <= e.which && e.which <= 65 + 25) || (97 <= e.which && e.which = max_chars){
target.val(target.val().slice(0,max_chars + num_enters – 1));
total_chars = max_chars;
if(e.which == 8){
remaining_chars_current_line += 1;
current_line_chars -= 1;
total_chars -= 1;
if(total_chars < 0){
total_chars = 0;
num_enters = 0;
}
}
}
else{
if(e.which == 8){
remaining_chars_current_line += 1;
current_line_chars -= 1;
total_chars -= 1;
if(total_chars max_chars_per_line){
remaining_chars_current_line = max_chars_per_line;
current_line_chars = 0;
}
if(remaining_chars_current_line < 0){
target.val(target.val() + "\n");
remaining_chars_current_line = max_chars_per_line – 1;
current_line_chars = 0;
num_enters += 1;
}
}
indicator.text("(Caracteres restantes: " + (max_chars – total_chars) + ")");
//}
});
}
Thx!
#14 by mi bush on October 13th, 2009
Quote
bug: if change limit from smaller to bigger indikator is changed but I can not write more characters
example:
$(document).ready(function() {
$(’#p’).maxChar(200, {indicator:’od’});
$(”humpo”).change(function(){
$(’#p’).maxChar(1000, {indicator:’od’});
};
};
Pingback: 5 New jQuery Plugins I bet You have not seen before | tripwire magazine
#15 by wptidbits on October 17th, 2009
Quote
Thanks for the great plugin. I do not know that we can count remaining char using jQuery. Anyway, its good if we can count post char too. This is just great a plugin!
Pingback: Come mostrare il numero di caratteri rimanenti in un form con jQuery | Pecciola
#16 by Rulatir on November 22nd, 2009
Quote
Very substandard solution.
- when on limit (0 remaining) the caret sticks to the end of input (but can be moved with mouse)
- if you position caret in the middle of input while on limit (0 remaining) and type a character, it stays there, and instead a character from the _end_ of the input disappears.
Worthless.
#17 by Mitch Wilson on November 22nd, 2009
Quote
Rulatir,
Thanks for the feedback. You’re right: that makes no sense. I created an issue to fix that here http://plugins.jquery.com/node/11505.
The solution would be an option for the plugin to not remove characters from the end when over the limit. For example, Twitter displays negative characters.
#18 by Jayde on November 30th, 2009
Quote
Re: Rulatir
Totally uncalled for to say someone’s work is worthless. Especially when they are providing it for free. Yes it does have a bug in it and it’s renders this plugin unusable for you (and me).
But, if you look back to the comments it looks like Mitch is working on this actively. If you don’t like his plugin move on and find another.
Calling it worthless does not motivate someone to fix something for you, again, for free.
I think this plugin has great promise once he fixes that bug. I love how you can customize the feedback text and place it where you like very easily.
#19 by al on December 30th, 2009
Quote
Hi Mitch,
I found another issue. Hopefully it is not a local problem only
This is how the problem occurs: define a limit of 500 chars so that the textarea will have a scrollbar. Now you enter 500 chars. The result: the textarea jumps to the beginning (cursor still sits at the end after the 500th char). If you try to scroll down the update mechanism always jumps back to the top.
Would be better if in this case on update would stay as it is so that you can still edit the last word you just entered.
Do you have an idea how to fix this? Would be great.
Thanks for this great plugin.
al
#20 by Mitch Wilson on December 31st, 2009
Quote
@ Jayde, thanks so much for the kind words. I’m sorry the plugin does have that bug. I have time to work on this on and off, and will be releasing a new version soon. About the word “worthless”: it does sound a bit harsh but it’s true, so I don’t mind and appreciate the feedback above all. I want this plugin to work. Period. I’ll email you when that issue is fixed. Again, thanks!
@al, I will look into this and fix it. Thank you for the feedback. I appreciate it greatly!
#21 by Mitch Wilson on December 31st, 2009
Quote
@mi bush, the code you pasted has some errors, probably due to copy/paste. But I see your point. This code illustrates the bug. The indicator says “15 remaining” but the limit remains 10 characters. I will look into this. Thanks!
$(document).ready(function(){
$(’#p’).maxChar(10, {indicator:’od’});
$(’#p’).maxChar(15, {indicator:’od’});
});
#22 by Mitch Wilson on January 1st, 2010
Quote
Ok, I’ve fixed the issues reported. See the new blog post about version 0.3.0.
The big fix was removing the truncation of characters over the limit. Instead, I took the twitter approach to simply display the number of characters over the limit as negative numbers in the indicator.
Since I removed truncation of the user’s text, I did add an option to truncate the text on form submission. So when a user submits the form, only the allowed number of characters are submitted, even though the form still displays them. This is a new option named truncate. The default is true but can be set to false using the settings object.
I did not address XZero’s request to add limits with respect to rows. I am requesting more information about that, though.
Happy New Year!
#23 by Rulatir on January 3rd, 2010
Quote
Re: jayde
> Totally uncalled for to say someone’s work is worthless.
As you can see, Mitch has since “fixed” the bug by removing the buggy feature: now you no longer have realtime enforcement of the limit, and as a bonus you get a violation of what-you-see-is-what-you-submit principle.
Considered harmful.
#24 by Mitch Wilson on January 3rd, 2010
Quote
@Rulatir Good point. The behavior should be to not submit the form. Thanks for the feedback.
In the meantime, to disable truncation on form submit, set truncate to false like this.
$(document).ready(function(){
// Pass HTML element id and character limit.
$(’#message’).maxChar(50, {truncate:false});
});
See the main page for more examples.
#25 by Mitch Wilson on January 3rd, 2010
Quote
NOTE: This post and most of these comment were about the original 0.1.0 version. For the newest 0.3.0 version and future updates, check out the main maxChar page.
VERSION 0.3.0 IS OUT (SEE ABOVE) AND VERSION 0.4.0 TO BE RELEASED SOON
To address the usability issue with truncation raised by Rulatir, I am replacing the truncate option with a new option called validate. By default validate option is true. If true, the plugin will disable the submit button if any of the fields’ character limit has been exceeded. Here is a sneak peek at the code so far. Also note the other new option, warningThreshold, regarding the number of characters to set a warning class on the indicator. The new code will have pass, warning and fail states to set a class on the indicator, which lets you mimic Twitter’s appoarch of changing the text color from green, to orange, to red.
/**
*
*
* SNEAK PEEK – FINAL 0.4.0 VERSION TO BE RELEASED SOON.
*
*
*
* maxChar jQuery plugin
* @author Mitch Wilson
* @version 0.4.0 (NOT FINAL – SNEAK PEEK)
* @requires jQuery 1.3.2 (only version tested)
* @see http://mitchwilson.net/maxchar/
* @param {Boolean} debug Specify whether to send message updates to the Firebug console. Default is false.
* @param {String} indicator Specify alternate indicator element by id. Default is indicator created dynamically.
* @param {String} label Specify a default label displayed when input element is not in focus. Default is blank.
* @param {String} pluralMessage Set the plural form of the remaining count message. Default is ‘ remaining’.
* @param {Number} rate Set the update rate in milliseconds. Default is 200.
* @param {String} singularMessage Set the singular form of the remaining count message. Default is ‘ remaining’.
* @param {String} spaceBeforeMessage Set spacing in front of (to the left of) the indicator message. Default is ‘ ‘.
* @param {Boolean} validate Whether to perform limit validation and enable/disable form submission. Default is true.
* @param {Number} warningThreshold The character count to set the warning CSS class on the indicator. Default is 10.
* @description Enforces max character limit on any input or textarea HTML element and provides user feedback and many options.
* New features added in 0.4.0 are:
* 1) Feature change: Option truncate removed due to usability concerns.
* 2) New Feature: Form submit button disabled when over limit. Plugin automatically finds the submit button in the parent form.
* 3) New Feature: pass, warning and fail states for the indicator. Sets CSS classes limit_pass, limit_warn or limit_fail.
*/
(function($){
$.fn.maxChar = function(limit, options) {
// Define default settings and override w/ options.
settings = jQuery.extend({
debug: false,
indicator: ‘indicator’,
label: ”,
pluralMessage:’ remaining’,
rate: 200,
singularMessage: ‘ remaining’,
spaceBeforeMessage: ‘ ‘,
validate: true,
warningThreshold: 10
}, options);
// Get maxChar target element.
var target = $(this); // Must get target first, since it is used in setting other local variables.
// Get settings.
var debug = settings.debug;
var indicatorId = settings.indicator;
var label = settings.label;
var pluralMessage = settings.pluralMessage;
var rate = settings.rate;
var singularMessage = settings.singularMessage;
var spaceBeforeMessage = settings.spaceBeforeMessage;
var validate = settings.validate;
var warningThreshold = settings.warningThreshold;
// Set additional local variables.
var currentMessage = ”; // Current message to display to the user.
var indicator = getIndicator(indicatorId); // Element to display count, messages and label.
var limit = limit; // Character limit.
var remaining = limit; // Characters remaining.
var timer = null; // Timer to run update.
var parent_form = $(this).closest(”form”);
var submit_button = parent_form.find(’input[type=submit]‘);
// Initialize on page ready.
if(label) {
indicator.text(label);
} else {
// Call update once on code initialization to update view if text is already in textarea,
// eg, if user relaoads page or hits back button and form textarea retains previoulsy entered text.
update(limit);
}
// When user focuses on the target element, do the following.
$(this).focus(function(){
if(timer == null) {
if(label) {
indicator.fadeOut(function(){indicator.text(”)}).fadeIn(function(){start()});
} else {
start();
}
}
});
// When user removes focus from the target element, do the following.
$(this).blur(function() {
// Stop timer that updates count and the indicator message.
stop();
// Update view.
if(label) {
indicator.fadeOut(function(){indicator.text(label)}).fadeIn();
}
});
// Disabled the submit button and form submission.
function disableSubmit() {
submit_button.attr(’disabled’, ‘disabled’);
}
// Enable the submit button and form submission.
function enableSubmit() {
submit_button.removeAttr(’disabled’);
}
function getIndicator(id){
// Get indicator element in the dom.
var indicator = $(’#'+id);
// If indicator element does not already exist in the dom, create it.
if(indicator.length == 0) {
target.after(spaceBeforeMessage + ‘‘);
indicator = $(’#'+id)
}
// Return reference to indicator element.
return indicator;
}
function isValid() {
var fail = $(’.limit_fail’);
return ! (fail.length);
}
// Handle limit error.
function limitFail() {
indicator.addClass(”limit_fail”);
indicator.removeClass(’limit_pass’);
indicator.removeClass(”limit_warn”);
if(validate) {
disableSubmit();
}
}
// Handle limit pass.
function limitPass() {
indicator.removeClass(”limit_fail”);
indicator.addClass(’limit_pass’);
indicator.removeClass(”limit_warn”);
if(validate) {
if(isValid()) {
enableSubmit();
} else {
disableSubmit();
}
}
}
// Handle limit error.
function limitWarn() {
indicator.removeClass(”limit_fail”);
indicator.removeClass(’limit_pass’);
indicator.addClass(”limit_warn”);
if(validate) {
if(isValid()) {
enableSubmit();
} else {
disableSubmit();
}
}
}
// Create helper functions.
function log(message) {
// Display
if(debug) {
try {
if(console) {
console.log(message);
}
} catch(e) {
// Do nothing on error.
}
}
}
// Start the timer that updates indicator.
function start() {
timer = setInterval(function(){update(limit)}, rate);
}
// Stop the timer that updates the indicator.
function stop() {
if(timer != null) {
clearInterval(timer);
timer = null;
}
}
// Update the indicator.
function update(limit){
var remaining = limit – target.val().length;
// Respond to remaining.
if(remaining < 0) {
limitFail();
} else if(remaining < (warningThreshold + 1) ) {
limitWarn();
} else {
limitPass();
}
if(remaining == 1) {
currentMessage = remaining + singularMessage;
} else {
currentMessage = remaining + pluralMessage;
}
// Update indicator.
indicator.text(currentMessage);
log(currentMessage);
}
};
})(jQuery);