1. Home
  2. Computing & Technology
  3. Perl

Working with CGI.pm In-Depth

Creating Checkboxes

From About.com

For our first look at creating checkboxes via CGI.pm, let's look at making a single one - something you might use for a simple yes/no toggle in your forms. In this case, we're going to create a check box, checked by default, that lets us know the user is requesting more information. Something you might use to sign up for a mailing list:
print checkbox(
-name => 'more_info',
-value => 'yes',
-selected => 1,
-label => 'Would you like more info?');
Looking at the output, we see that this creates a checkbox with the name more_info and the value (if checked) yes. It is checked by default with checked="checked" and the label that surrounds it acts as the text informing the user of the checkboxes function:
<label><input type="checkbox" name="more_info" value="yes" checked="checked" />Would you like more info?</label>
Simple enough, right? But what happens when we want multiple boxes, say for a set of related options? Here's an example where we're setting a group of color options:
my %labels = (
'red' => 'A Red One',
'green' => 'A Green One',
'blue' => 'A Blue One',
'yellow' => 'A Yellow One' );

print checkbox_group(
-name => 'color_choices',
-values => ['red', 'green', 'blue', 'yellow'],
-default => ['red', 'blue'],
-labels => \%labels
);
And the output is:
<label><input type="checkbox" name="color_choices" value="red" checked="checked" />A Red One</label>
<label><input type="checkbox" name="color_choices" value="green" />A Green One</label>
<label><input type="checkbox" name="color_choices" value="blue" checked="checked" />A Blue One</label>
<label><input type="checkbox" name="color_choices" value="yellow" />A Yellow One</label>
So if we look at the differences, the first and most obvious is that we're setting up a hash with all the label values in it. This is the text that will appear alongside the checkbox describing what it does. That hash gets passed on via a pointer in the -labels option.

Next up we have the same -name attribute, and a slightly different -values attribute. Note the S on the end of the value, and the fact that it's now an array of values rather than a single value. Finally we set the -default checked values (in this case red and blue) and pass the -labels pointer.

Explore Perl

More from About.com

  1. Home
  2. Computing & Technology
  3. Perl
  4. CGI & Web
  5. Working with CGI.pm In-Depth - How to create checkboxes with CGI.pm

©2008 About.com, a part of The New York Times Company.

All rights reserved.