background image
HomeRecent PostsDrupalSearchTagsRSSContactAboutAccount

Improving form validation usability for checkboxes and radio buttons

Eric.London's picture

Normally when there is a form input error, Drupal highlights the form input by adding a red border and changing the text color. Unfortunately, nothing happens for checkboxes and radio buttons. Here's a little jQuery to add the error class to the label directly above a set of checkboxes or radios when an error occurs.

<?php
$('form#node-form div.form-item').each(function(){
  var
result = 0;
 
result += $(this).find('div.form-radios input.form-radio.error').length;
 
result += $(this).find('div.form-checkboxes input.form-checkbox.error').length;
  if (
result) $(this).find('label:first').removeClass('error').addClass('error');
});
?>

Add a Drupal.behaviors wrapper

Thanks for your blog! I'm really getting a lot out of it.

With the current version of Drupal (6.20), I added a Drupal.behaviors wrapper and the error class goes into the label tag as expected.

Drupal.behaviors.modulenameRadios = function (context) {
$('form#node-form div.form-item').each(function(){
var result = 0;
result += $(this).find('div.form-radios input.form-radio.error').length;
result += $(this).find('div.form-checkboxes input.form-checkbox.error').length;
if (result) $(this).find('label:first').removeClass('error').addClass('error');
});
}

Eric.London's picture

thanks

I can't say this enough.. I need to clean up my blog posts!

What do I actually do with this?

I'm not sure what to do with jQuery stuff - do I place this in template.php?

Use outline instead

In your CSS instead of border: 1px solid red
Use:
outline: 1px solid red !important

this will make the checkboxes and radios red