Uncategorized

jQuery Character Counter

First, Laurin Dodd of Computer products for Education mentioned that iPhone’s method of password masking (which masks ever character except the last one typed, and that’s only displayed for 2 seconds after the key is let up) was the most efficient.

Now, I wanted an easy way to be able to throw a character counter on a website. In fact, as many character counters as I need. Instead of write a jQuery plugin, I think it is easier to ID your fields and then specify a SPAN tag with the ID -chars; e.g. textarea #comments would have a span#comments-chars. The default value you put in the HTML is what the enforced maximum length of that control will be. It just seems more intuitive to have a <span id=”comments-chars”>200</span> and doing the appropriate checks, than doing $(“#comments”).charCounter(“#comments-chars”, 200).

Paste the function below into your JavaScript file, then call it to activate your character counters:

// Finds any elements where the ID ends in -chars, and then finds
// its corresponding element (same ID without the -chars), and sets it up
// to where the maximum length of the box is what HTML is in the -chars.
// by Derreck Dean www.derreckdean.com 2009 06 29
function setupCharCounters() {

$("[id$=-chars]").each(function() {
var charCounter = $(this);
var maximumChars = parseInt($(this).html());
var target = $("#" + $(this).attr("id").replace("-chars", ""));
target.attr("maxchars", maximumChars); // save this
target.keyup(function() {
var maxChars = $(this).attr("maxchars");
var value = $(this).attr("value");
var remain = maxChars - value.length;
if (remain < 0) {
remain = 0;
$(this).attr("value", value.substring(0, maxChars));
}
$("#" + $(this).attr("id") + "-chars").html(remain.toString());
});
});

}

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s