Here is a quick and simple jQuery plugin I wrote. All you need to do is $("#element_id").jqCounter();
to give an input or textarea a character counter. It responds to paste, changes and everything else I could think of.
You must set the maxlength attribute for it to work, ie. <input maxlength=45 />
or <textarea maxlength=45></textarea>
<script>
(function($) {
$.fn.extend({
jqCounter : function(givenOptions) {
return this.each(function() {
var $this = $(this),
options = $.extend({
divider: "/" // The diveder character between the count and max
}, givenOptions);
// 0 chars or max count not set or already setup
if($this.attr("maxlength") <= 0 || $this.hasClass("jqCounter")) return;
// Add the counter text after the element
var span= $("<span style=\"font-size:10px;\">"+$this.val().length+options.divider+$this.attr("maxlength")+"</span>")
.insertAfter($this);
// Add a class
$this.addClass("jqCounter")
// React to keypresses, changes, paste, etc. and change the counter
.on('focus blur propertychange change input paste keydown keyup keypress', function(){
setTimeout(function(){
var maxChars = $this.attr("maxlength"),
txtLength = $this.val().length;
span.text( txtLength + options.divider + maxChars );
},
1);
});
});
}
});
})(jQuery);
$(document).ready(function()
{
// All text areas will have a content counter
$("textarea").jqCounter();
});
</script>