Monday 2 July 2012

Adding a word counter to webform


The hardest part of implementing a word counter was finding one that looks good and works. A surprisingly difficult task. We settled on the very slick jQuery Word Counter. I like Trevor’s style of explaining how he implemented an idea, what was going through his head and why he made his programmatic decisions. That knowledge is helpful for all levels of technical expertise and for any size project.

His demo lives in the cloud.

To implement a ’250 word’ word counter in webform:

Download the source and save it in sites/all/themes/YOUR_THEME/word-count.js.
Edit word-count.js and change this line
$("[class^='count[']").each(function() {
to this

$("[class*=' count[']").each(function() {
Now the CSS selector will look for a class that “contains” count instead of “starts with.”

Find the node id of the webform you would like to edit. In this example, node id 907.
Copy sites/all/modules/webform/webform-form.tpl.php to sites/all/modules/YOUR_THEME/webform-form-907.tpl.php (replace 907 with your node id)
Edit webform-form-907.tpl.php and add the following line just before drupal_render($form['submitted']).
  $form['submitted']['letter_body']['body']['#attributes'] =
      array('class' => 'count[250]');
The letter_body in my example is a fieldset, with body being the textarea I want to add the counter to. See the webform configuration from a related blog post.

So we’ve downloaded the .js file, told webform to add class=”count[250]” so that jQuery knows how to reference the textarea, now we just need to tell Drupal to include the .js file in our page. In Drupal 6 it’s a piece of cake. Simple add
scripts[] = word-count.js
to your sites/all/themes/YOUR_THEME/YOUR_THEME.info file.

Now clear your Drupal cache by reloading your theme in Site Building -> Themes and verify the counter works.
Read the project page to learn more about configuring the min/max words and make the appropriate changes in the .tpl.php file.

1 comment: