Code

Validating check boxes and radio buttons with Prototype

The title might be misleading, but the kind of validation I was after is checking whether or not at least one option in a group of elements (check boxes or radio buttons) is checked.

This is useful in cases where you want the user to make a choice on their own instead of accepting a default value, or in cases where you can’t supply a default one. I wanted the validation to take place at client-side, before posting the form, so JavaScript is the only option.

I tried different approaches to this matter, but wound up with using the Prototype JavaScript framework which allowed me to construct an efficient little one-liner:

$( "elements" ).pluck( ‘checked’ ).sort().uniq().find( function( b ) { return b; } );

Replace the elements selector with your own. Just make sure it returns a collection of checkboxes or radio buttons. It will return boolean true if at least one of the elements is checked, otherwise false.

5 Comments

speak up

Add your comment below, or trackback from your own site.

Subscribe to these comments.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

*Required Fields