n.r. n.r. - 2 months ago 6
Perl Question

How to create an HTML attribute without a value

How can I create an HTML element with an attribute that lacks a value?

For example, the

checked
attribute usually doesn't have any value, like this:

<input checked name="field" type="checkbox" />


The MWE below, however, gives us a
checked
attribute with an empty string as value.

<input checked="" name="field" type="checkbox" />


MWE:

use HTML::Element;
my $h = HTML::Element->new ( 'input' );

$h->attr ( type => 'checkbox' );
$h->attr ( name => 'field' );
$h->attr ( checked => '' );

print STDOUT $h->as_HTML, "\n";

Answer

EDIT: ThisSuitIsBlackNot has the correct solution above:

$h->attr ( checked => 'checked' );

that works. If he adds it as an answer, I'll delete mine. Not sure how one could derive that from the documentation, however... If it is out there somewhere, I would love to have someone point me to it.

OLD SOLUTION: Not a perfect solution, but I got it to work doing the following:

use HTML::Element;
my $h = HTML::Element->new ( 'input', 'checked' );

$h->attr ( type => 'checkbox' );
$h->attr ( name => 'field' );

print STDOUT $h->as_HTML, "\n";

which produces this:

<input checked name="field" type="checkbox" />

but there must be a better way of doing this....

The CPAN documentation states the following:

Note that setting an attribute to undef (as opposed to "", the empty string) actually deletes the attribute.

which is the reason $h->attr ('checked'); doesn't work, but there must be a way to add a non-value attribute after element creation. It's just not obvious (at least to me) on how to do it.

Comments