Monday 2 July 2012

Adding a javascript counter to your drupal forms


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. countdownand a limit specification (for how many characters you want to limit to.

<textarea cols="40" rows="4" name="title" id="edit-title"  value=""></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=""></textarea>
<br />
<span><!-- --></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’
);
?>


Module =====http://drupal.org/project/maxlength========

No comments:

Post a Comment