Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid

Dynamically marking a HTML select option as selected

by ezekiel (Pilgrim)
on Dec 19, 2001 at 10:05 UTC ( #133024=perlquestion: print w/ replies, xml ) Need Help??
ezekiel has asked for the wisdom of the Perl Monks concerning the following question:

I have an CGI application where a user can create a database entry by completing an HTML form. Later, the user may want to retreive an entry, edit it, and store it back in the database. I plan to do this by extracting the values from the database and producing the same HTML form but with these values inserted as the "default" values.

This works fine for text boxes by just adding a  value="$existing_value" to the <input type="text" name="my_parameter"> widget. However, I run into a problem when using a <select> widget.

The only way I can think of doing it is to put it inside an if/then statement as such:

if ($existing_value eq "option1") then { $html .= qq| <select name="my_parameter"> <option value="option1" selected>Option 1 <option value="option2">Option 2 </select> |; } elsif ($existing_value eq "option2") then { $html .= qq| <select name="my_parameter"> <option value="option1">Option 1 <option value="option2" selected>Option 2 </select> |; }

This is really ugly, especially if the select has a large number of possible options. Does anyone have any better suggestions as to how this might be done? Any modules that may help?


Comment on Dynamically marking a HTML select option as selected
Select or Download Code
Replies are listed 'Best First'.
Re: Dynamically marking a HTML select option as selected
by chip (Curate) on Dec 19, 2001 at 12:03 UTC
    How's this:

    $html .= qq[<select name="foo">]; for ('option1:One', 'option2:Two') { my ($val, $desc) = split /:/; my $sel = ($val eq $existing_value) ? ' selected' : ''; $html .= qq[<option value="$val"$sel>$desc]; } $html .= qq[</select>];

        -- Chip Salzenberg, Free-Floating Agent of Chaos

Re: Dynamically marking a HTML select option as selected
by Chmrr (Vicar) on Dec 19, 2001 at 13:11 UTC

    It's not overly flexible in terms of layout, but one should mention the solution if only for completeness:

    $html .= $query->radio_group(-name => "my_parameter", -values => [qw/option1 option2/], -default => $existing_value, -labels => {option1=>"Option 1", option2=>"Option 2"}, -linebreak => "true");

    It seems that uses "checked" instead of "selected", despite that selected is the spec. For more copious options, see your local documentation.

    Update: In my sleep-deprived state, I somehow saw "drop-down list" and thought "radio group." Don't ask about the details. Anyways, all of the above does apply to popup_menu as well as radio_button, as mortis points out. Memo to self: Engage brain before noding.

    perl -pe '"I lo*`+$^X$\"$]!$/"=~m%(.*)%s;$_=$1;y^`+*^e v^#$&V"+@( NO CARRIER'

      I applaud you mentioning, it does have a solution - it's just not the radio_group method, it's popup_menu, or scrolling_list, depending on weather you want a single selection drop-down or a multi-value scrolling list box.
      $html .= $query->scrolling_list( -name => 'my_parameter', -values => [qw/option1 option2/], -default => $existing_value, -labels => { option1 => 'Option 1', option2 => 'Option 2'}, -multiple => 'true', ); # or $html .= $query->popup_menu( -name => 'my_parameter', -values => [qw/option1 option2/], -default => $existing_value, -labels => { option1 => 'Option 1', option2 => 'Option 2'}, );
      The other absolutely wonderful thing about is that if the parameter already has a value in the $query object (which you can set explicitly), it will automaticly have it's old value (i.e. it will stick) when you use $query to produce the html (that is if you don't set it explicitly as above). This is great for situations when you have to re-display an HTML page with a form to the user so they can either correct fields, or fill in required fields.

      If you want to have a default value without overwriting the user's entry, an easy thing to do is:

      $query->param('my_parameter',$defaultValue) unless defined $query->p +aram('my_parameter');


Re: Dynamically marking a HTML select option as selected
by joealba (Hermit) on Dec 19, 2001 at 10:36 UTC
    Quick and dirty way: Just use a regexp to add in the 'selected' string if your default value exists. You may want to do some extra error checking too, like making sure that your default value is a valid option.
    my $parameter_value = "option2"; # Your default value from the DB my $parameter_select = qq( <select name="parameter"> <option value="option1">Option 1 <option value="option2">Option 2 </select> ); # your select statement string if ($parameter_value) { $parameter_select =~ s/value="$paremeter_value"/value="$paremeter_va +lue" selected/; }
Re: Dynamically marking a HTML select option as selected
by Juerd (Abbot) on Dec 19, 2001 at 12:45 UTC
    How about
    $html .= qq{<select name="my_parameter">\n}; for my $option ( ['option1', 'Option 1'], ['option2', 'Option 2'], ['option3', 'Apple pie'] ){ if ($option->[0] eq $existing_value){ $html .= qq{<option value="$option->[0]" selected>$option->[1]</opti +on>\n}; }else{ $html .= qq{<option value="$option->[0]">$option->[1]</option>\n}; } } $html .= "</select>\n";
    The inside could be rewritten as:
    $html .= qq{<option value="$option->[0]"} . ($option->[0] eq $existing_value ? ' selected' : '') . qq{>$option->[1]</option>\n};
    And you should think about using entities, 'cause an $existing_value with a " in it isn't going to make you happy...

    2;0 juerd@ouranos:~$ perl -e'undef christmas' Segmentation fault 2;139 juerd@ouranos:~$

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://133024]
Approved by root
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others surveying the Monastery: (6)
As of 2015-12-01 01:54 GMT
Find Nodes?
    Voting Booth?

    What would be the most significant thing to happen if a rope (or wire) tied the Earth and the Moon together?

    Results (791 votes), past polls