Check for a radio in that box
--#--
Checkboxes and radio buttons are deceptively similar.
The main difference to watch out for is that radio buttons tend
to come in groups, with the buttons in each group having the same
name but different value fields.
The bottom line is that you can treat checkboxes almost like text
fields:
@cbs = getCheckBoxes($html_file);
foreach(@cbs) {
$val = $query->param($_);
if (length($val) > 0) {
$html_file =~ s/(name="?$_[^>]*)>/$1 CHECKED>/si;
}
}
sub getCheckBoxes {
my($html) = @_;
my @c = ();
my @boxes = split(/type="?checkbox/i, $html);
for (1..@boxes - 1) {
if ($boxes[$_] =~ /name="?([\-\w]*)"?/i) {
push(@c, $1);
}
}
return @c;
}
But radio buttons need different treatment altogether. The first thing
to look out for, get a list of unique group names. If you simply
split on radio and push each name, you'll get an array full of
duplicates. You need to check the array first to see that
name has already been pushed:
if ($radios[$_] =~ /name="?([\-\w]*)"?\s+/i && !grep(/$1/, @r)) {
push(@r, $1);
}
grep looks into the array to see if the backreferenced match is
there. If not !, it gets pushed. Once you have an array of names,
match on the name's value, not the name itself. Complete radio code:
@radios = getRadios($html_content);
foreach(@radios) {
$val = $query->param($_);
$html_content =~ s/(value="?$val[^>]*)>/$1 CHECKED>/si;
}
sub getRadios {
my($html) = @_;
my @r = ();
my @radios = split(/type="?radio/i, $html);
for (1..@radios - 1) {
if ($radios[$_] =~ /name="?([\-\w]*)"?\s+/i && !grep(/$1/, @r)) {
push(@r, $1);
}
}
return @r;
}