Alessandro Melandri

WebSphere Commerce Specialist, project manager, wannabe photographer

Textarea Char Counter, a jQuery Plugin

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.

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:

1
2
3
<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:

1
2
3
4
5
<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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
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

1
2
3
4
5
// Add a simple counter
$('#textarea1').setCounter();

// Add a counter and set maximum length to 500 characters
$('#textarea2').setCounter(500);