jQuery: Characters Remaining

I needed a counter on my input texts to say how many characters are left, so I came up with this. It creates a yellow box to the right of the input area, which is updated when the field is edited.

Counter Function

<?php
jQuery
.fn.counter = function() {
  $(
this).each(function() {
    var
max = $(this).attr('maxlength');
    var
val = $(this).attr('value');
    var
cur = 0;
    if(
val) // value="", or no value at all will cause an error
     
cur = val.length;
    var
left = max-cur;
    $(
this).after("<div class='counter'>"
     
+ left.toString()+"</div>");
   
// You can use something like this to align the
    // counter to the right of the input field.
   
var c = $(this).next(".counter");
   
c.width(40);
   
c.css("position","relative");
   
c.css("top",-$(this).height()-8);
   
c.css("left",$(this).width()+8);
   
c.css("background","yellow");
 
    $(
this).keyup(function(i) {
      var
max = $(this).attr('maxlength');
      var
val = $(this).attr('value');
      var
cur = 0;
      if(
val)
       
cur = val.length;
      var
left = max-cur;
      $(
this).next(".counter").text(left.toString());
      return
this;
    });
  });
  return
this;
}
?>

Usage Examples

You'd use it like the following. In the example, #main is the main body area, and all fields will have a class of maxlength which need the counter.

<?php
$(document).ready(function() {
  $(
"#main form input.maxlength").counter();
});
?>

Or you could search for any fields with a maxlength attribute:

<?php
$(document).ready(function() {
  $(
"form input[@maxlength]").counter();
});
?>

Submitted by Brad Landis on February 26, 2007 - 11:55pm. categories [ ]

Can you give an example of

Can you give an example of how to get this working with textarea controls?
Thanks

Textarea Has No Maxlength

Textarea doesn't have a maxlength, so it would have to be completely different. Basically, you'd have to hardcode the length, and use javascript to keep the user from typing more text than they should.

How to use on CCK?

I have text fields in CCK, do you know how to use this script alongside

Hm, I'm not sure on that. It

Hm, I'm not sure on that. It would take a custom module, and including the javascript in the file.