[nycphp-talk] Remembering which option in a SELECT the user picked.
Jerry Kapron
jkapron at NewAgeWeb.com
Wed Jan 29 12:29:36 EST 2003
...
>In the reprinted SELECT tag, one of the OPTION tags will now have a
SELECTED
>attribute. Is there any elegant way to insert the SELECTED attribute on
>the right option?
First create an array with all your options for the <select> menu:
$TimeChoice_options = array(
'Friday August 22, 04:00 PM - 06:00 PM',
'Friday August 22, 06:00 PM - 08:00 PM',
'Friday August 22, 08:00 PM - 10:00 PM',
...
);
Next define this function:
function make_select($source, $field_name, $selected_id = "")
{
echo '<select name="'.$field_name.'" id="'.$field_name."\\">\
";
foreach($source as $element)
{
if(is_array($element)
{
$id = $element[0];
$label = $element[1];
}
else
{
$id = $element;
$label = $element;
}
$sel = ($selected_id == $id)?' selected':'';
echo '<option value="'.$id.'"'.$sel.'>'.$label."</option>\
";
}
echo "</select>\
";
}
Now place this function call where you would like to have your <select> menu
built:
make_select($TimeChoice_options, 'TimeChoice',
$HTTP_GET_VARS['TimeChoice']);
Change $HTTP_GET_VARS to $HTTP_POST_VARS if you use method="POST" in your
form tag:
make_select($TimeChoice_options, 'TimeChoice',
$HTTP_POST_VARS['TimeChoice']);
In the future if your values and labels are different for your <select>
options:
<option value="1">Monday</option>
<option value="2">Tuesday</option>
<option value="3">Wednesday</option>
<option value="4">Thursday</option>
...
... just build a two-dimentional array instead (the above function is ready
for it):
$TimeChoice_options = array(
array( '1', 'Monday'),
array( '2', 'Tuesday' ),
array( '3', 'Wednesday'),
array( '3', 'Thursday'),
...
);
Good Luck,
Jerry
--
42.7% of all statistics are made up on the spot.
More information about the talk
mailing list