Kind of simple question:
Is there a way to use the id
attribute for a radio group created with Perl's CGI::radio_group
correctly?
When I tried it, each <input>
element got the same ID, which most likely is not correct according to the example given in <input type="radio">
- HTML: HyperText Markup Language | MDN.
CodePudding user response:
Please don't use the HTML generation functions from CGI.pm. We've known they are a terrible idea for at least 20 years. The current documentation for CGI.pm contains this text:
HTML Generation functions should no longer be used
All HTML generation functions within CGI.pm are no longer being maintained. Any issues, bugs, or patches will be rejected unless they relate to fundamentally broken page rendering.
The rationale for this is that the HTML generation functions of CGI.pm are an obfuscation at best and a maintenance nightmare at worst. You should be using a template engine for better separation of concerns. See CGI::Alternatives for an example of using CGI.pm with the Template::Toolkit module.
These functions, and perldoc for them, are considered deprecated, they are no longer being maintained and no fixes or features for them will be accepted. They will, however, continue to exist in CGI.pm without any deprecation warnings ("soft" deprecation) so you can continue to use them if you really want to. All documentation for these functions has been moved to CGI::HTML::Functions.
Really, they are a terrible idea. Using them will make your life harder than it needs to be. Putting real HTML in a template file is a far better idea.
Having said that, if you insist on doing the wrong thing, you can use the optional -attribute
parameter to the radio_group()
function (as documented in CGI::HTML::Functions(3pm)
for radio_group()
). It takes a hash reference. The keys in hash are the values of the radio buttons and the associated values are references to other hashes that map attribute names onto values.
#!/usr/bin/perl
use strict;
use warnings;
use feature 'say';
use CGI 'radio_group';
my @radios = qw[foo bar baz];
my %attributes = (
foo => { id => 'FOO' },
bar => { id => 'BAR' },
baz => { id => 'BAZ' },
);
say radio_group(
-name => 'radio',
-values => \@radios,
-attributes => \%attributes,
);
This produces the following HTML (when tidied up a bit):
<label>
<input type="radio" name="radio" value="foo" checked="checked" id="FOO"/>foo
</label>
<label>
<input type="radio" name="radio" value="bar" id="BAR"/>bar
</label>
<label>
<input type="radio" name="radio" value="baz" id="BAZ"/>baz
</label>
Did I make it clear enough that you shouldn't do this?