Some weeks ago I received a customer request to add a character counter to a textarea field and I made it using “classic” Javascript. Now that I’m learning jQuery and have some spare time, I tryed to transform my custom function to a jQuery plugin.
This is my first attempt to build a jQuery plugin and maybe there’s already another plugin that does the same thing but it have been a really nice exercise.
Check out the plugin code and some more details after the break.
This plugin will give you the method setCounter([maxLength]). If you call it on a textarea field you will get a counter that gets updated every time the user write a character.
The maxLength parameter is not mandatory so if it’s undefined you will get a simple character counter like this:
<div id="textareaId_counter"> <span class="length">27</span> </div>
while if you pass an integer to the method the user won’t be able to write a number of character greater than maxLength and you will get a counter like this:
<div id="textareaId_counter"> <span class="length">27</span> <span class="sep">/</span> <span class="maxLength">500</span> </div>
This is the code. Save it in a text file named something like jquery.textareaCharacterCounter.js and include it in your page:
jQuery.fn.setCounter = function(maxLength){ return this.each(function(){ var jqthis = jQuery(this); if (jqthis.is('textarea')){ var counterId = jqthis.attr('id') + "_counter"; var htmlCounter = '<div id="' + counterId + '">'; htmlCounter += '<span class="length">' + jqthis.val().length + '</span>'; if (maxLength){ htmlCounter += '<span class="sep">/</span>'; htmlCounter += '<span class="maxLength">' + maxLength + '</span>'; } htmlCounter += '</div>'; jqthis.after(htmlCounter); jQuery('#'+counterId).width(jqthis.width()).css({ 'text-align':'right', 'margin-top':'10px' }); jqthis.bind("keyup",function(){ var content = jqthis.val(); if (maxLength && content.length > maxLength){ content = content.substring(0,maxLength) jqthis.val( content ); } jQuery('#' + counterId + " > span.length").text(content.length); }); } else { alert("Not applicable to element: " + jqthis); } }); }
How to use it
// Add a simple counter $('#textarea1').setCounter(); // Add a counter and set maximum length to 500 characters $('#textarea2').setCounter(500);