Chao Lam

Working on the next small things …

Javascript: Textarea/text field with UI for limiting max characters

leave a comment »

Want to build a Twitter clone? You’ll need a text field that limits text entry to 140 characters?

How ’bout one of those faddish question and answer sites (like alas our own failed) CoolQs? You’ll need the same widget that tells you how many characters you have left for your question.

You could use the MAXLENGTH or SIZE attributes for the <input> field. But that doesn’t provide the user with the instant feedback as to how many characters the user has left as the user types away.

Well, it’s your lucky day – I have just the widget for you if you use the Prototype library.

To turn any html text field or textarea, try

new TextLimiter<source elt>, <options>


new TextLimiter 'whatsup', {limit:140}

<source elt> is the text field or textarea object you want add TextLimiter behaviors to. You can specify the DOM id or the javascript object, as per standard Prototype classes.

Optional options (is that redundant?) include:

  • statusElt: DOM element to provide feedback as user types. is called when the user starts typing.
  • countElt: The DOM element usually within statusElt that is dynamically updated to show how many characters are left.
  • limit: the maximum number of characters allowed. Hard-coded default is 110.

Here’s the code:

var TextLimiter = Class.create();
TextLimiter.prototype = {
 initialize: function(textField, options) {
 //options: statusElt, countElt, limit
 this.textField = $(textField);
 this.options = Object.extend({limit:110}, options || {});
 var status = this.options.statusElt = $(this.options.statusElt);
 if (status) {status.hide();}
 this.options.countElt = $(this.options.countElt);
 this.textField.observe('keyup', this.keyUp.bindAsEventListener(this));
 this.textField.observe('focus', this.focus.bindAsEventListener(this));
 focus: function() {
 if (this.options.statusElt) {;}
 keyUp: function() {
 var field = this.textField;
 var limit = this.options.limit;
 if (field.value.length > limit) {
 field.value = field.value.substring(0, limit);
 } else if (this.options.countElt) {
 var total = limit - field.value.length;
 this.options.countElt.innerHTML = total;

Written by Pseudonymous

August 12, 2009 at 11:13 pm

Posted in Uncategorized

Leave a Reply

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

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

Google photo

You are commenting using your Google 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

%d bloggers like this: