in reply to nesting foreach statements

use CGI;

Let's say you have a group called "color" with values red, yellow and green, and you want to pre-select this in a form (where the field is also called "color").

In our example, you read in your data file and find the user has selected green. So:

my $q = new CGI; $q->param('color','green');
Then when creating form, print this
$q->radio_group(-name=>'color', -values=>['red','yellow','green']);
and the correct color will already be selected.

hth

cLive ;-)

Replies are listed 'Best First'.
Re: (cLive ;-)Re: nesting foreach statements
by Ogmios (Initiate) on Apr 07, 2002 at 00:01 UTC
    Thank you, but my problem is a bit more complex. I should try to explain better. 1) I have a form which contains a multichoice box in that format:
    <select name="colors" multiple size=5 "> <option>Blue <option>Red <option>Yellow <option>Green </select>
    2) When user fill out form, they can choose multiple options. After they submit, it saves the options into a flat text file, along with the other form's answer: userid|password|name|email|Blue,Red|comments 3) The user has the option to come back in later time and edit his info. It is prompted with an edit form on which his previous answers are already inserted. In this case I would need the edit form to present the "colors" field in this way:
    <select name="colors" multiple size=5 "> <option selected>Blue <option selected>Red <option>Yellow <option>Green </select>
    I am limited with perl and I have tried to basically read the array from the choice of colors: @colors = ("Blue","Red","Yellow","Green"); make the chosen colors scalar into an array and read it: @chosen = ("Blue","Red"); an then tried to compare both but all I can come up with is a bunch of nested foreach statements which is not good:
    foreach colors { foreach chosen { if $chosen eq $color { $editchosen = <option selected>$color } else { $editchosen = <option>$color } } }
    Anyway, you can tell that I am not starting well with my thinking. Help! Thank you.
      Like this?
      #!/usr/bin/perl -w use strict; use CGI; my $q = new CGI; my @colors = qw(red yellow pink green orange purple blue); my @chosen = qw(red green purple); print $q->header, $q->start_html, $q->start_form, $q->scrolling_list(-name => 'color', -values => \@colors, -default => \@chosen, -size => 5, -multiple => 'true' ), $q->submit, $q->end_form, $q->end_html; exit(0);
      cLive ;-)