﻿jQuery.fn.counter = function() {
  $(this).each(function() {
    //var max = $(this).attr('maxlength');
    var max = 250;
    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()+" CHARACTERS REMAINING</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(30);
    c.css("float","left");
    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 max = 250;
      var val = $(this).attr('value');
      var cur = 0;
      if(val)
        cur = val.length;
      var left = max-cur;
      $(this).next(".counter").text(""+ left.toString()+" CHARACTERS REMAINING");
      if(cur > max)
      {
        $(this).val(val.substring(0, max));
      }
      return this;
    });
  });
  return this;
}
