Categories
Programming

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

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.

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

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

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