adding a javascript counter to your drupal forms

user warning: Table './johnandcailincmsdb/node_counter' is marked as crashed and should be repaired query: SELECT totalcount, daycount, timestamp FROM node_counter WHERE nid = 66 in /var/www/drupal/includes/database.mysql.inc on line 172.

if you want to add a javascript counter (n characters remaining) to your drupal forms, you can do the following (jquery code based very heavily on the jquery tricks on reindel.com)

1. add two new classes to your text area

add two new css classes to your text area i.e. countdown and a limit specification (for how many characters you want to limit to.
<textarea cols="40" rows="4" name="title" id="edit-title"  value="" class="form-text required countdown limit_100_"></textarea>

2. create a span where you want your n remaining characters to go

<textarea cols="40" rows="4" name="title" id="edit-title"  value="" class="form-text required countdown limit_100_"></textarea>
<br />
<span class="remaining"><!-- --></span>

3. finally, splonk in your jquery code

<?php
drupal_add_js
(
'$(document).ready(function()
{
      var countdown = {
        init: function() {
            countdown.remaining = countdown.max - $(countdown.obj).val().length;
            if (countdown.remaining < 0)
            {
               countdown.remaining = 0;
               $(countdown.obj).siblings(".remaining").addClass("error");
            }
            else
            {
               $(countdown.obj).siblings(".remaining").removeClass("error");
            }    
            if (countdown.remaining > countdown.max) {
                $(countdown.obj).val($(countdown.obj).val().substring(0,countdown.max));
            }
            $(countdown.obj).siblings(".remaining").html(countdown.remaining + " characters remaining.");


        },
        max: null,
        remaining: null,
        obj: null
    };
    $(".countdown").each(function() {
        $(this).focus(function() {
            var c = $(this).attr("class");
            countdown.max = parseInt(c.match(/limit_[0-9]{1,}_/)[0].match(/[0-9]{1,}/)[0]);
            countdown.obj = this;
            iCount = setInterval(countdown.init,1000);
        }).blur(function() {
            countdown.init();
            clearInterval(iCount);
        });
    });
});'
,
'inline'
);
?>

Appendix: Drupal Modules

Alex aka a_c_m tells me that he's just upgraded the maxlength drupal module to have the functionality I've described. I haven't checked it out but you probably should!
Please note, this entry has been closed to new comments.