On Wed, 24 Oct 2001, Peggy Redle wrote:
> I need some guidance in dealing with radio buttons.
>
> How do you pass in values? How can you set the checked attribute based
> on that value? How do I get the value from the chosen option?
This is what I do, and the same holds for list boxes:
I have an array containing my radio button labels, and checked state
and assume that the value to be checked is in a variable called
$radio_value
my @radio = (
{ value => 'value1', checked => ($radio_value eq 'value1')},
{ value => 'value2', checked => ($radio_value eq 'value2')},
{ value => 'value3', checked => ($radio_value eq 'value3')}
);
$template->param(radio => \@radio);
<tmpl_loop radio>
<input type="radio"
name="my_radio"
value="<tmpl_var value>"
<tmpl_if checked>checked</tmpl_if>> <tmpl_var value><br>
</tmpl_loop>
Now, although this code works, it's a little tedious, so I generally
replace it with something like this:
my @radio = (
{value=>'value1'},
{value=>'value2'},
{value=>'value3'}
);
for (@radio) {
if($_->{'value'} eq $radio_value) {
$_->{'checked'} = "checked";
} else {
$_->{'checked'} = "";
}
}
<tmpl_loop radio>
<input type="radio" name="my_radio"
value="<tmpl_var value>" <tmpl_var checked>> <tmpl_var value><br>
</tmpl_loop>
Hope this helps. I've used it on several projects, and it scales well,
even if values are read from a database/file. For multiselect lists or
checkboxes, the only difference is that $radio_value is now
@radio_value, and another loop is used to check. I personally prefer
this instead:
$radio_values = join "\000", @radio_values;
for (@radio) {
$value = $_->{'value'};
if( $radio_values =~ /(^|\000)$value(\000|$)/ ) {
$_->{'checked'} = "checked";
} else {
$_->{'checked'} = "";
}
}
Of course, you'd want to use (?:) instead in that pattern match.
Philip
--
The goal of Computer Science is to build something that will last at
least until we've finished building it.
Visit my webpage at http://www.ncst.ernet.in/~philip/
Read my writings at http://www.ncst.ernet.in/~philip/writings/
MSN philiptellis Yahoo! philiptellis
AIM philiptellis ICQ 129711328
---------------------------------------------------------------------
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]