Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

Dynamically marking a HTML select option as selected

by ezekiel (Pilgrim)
on Dec 19, 2001 at 10:05 UTC ( [id://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?

Thanks.

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 CGI.pm 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 CGI.pm uses "checked" instead of "selected", despite that selected is the spec. For more copious options, see your local CGI.pm 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 CGI.pm, 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 CGI.pm 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');

      hth

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?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others lurking in the Monastery: (5)
As of 2024-03-28 17:31 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found