<?php
$options = $_GET['options'];
switch ($options)
{
case 'option1' :
$option1_select = 'selected';
break;
case 'option2' :
$option2_select = 'selected';
break;
case 'option3' :
$option3_select = 'selected';
break;
}
$select_box = '
<select name="options" >
<option value="option1" '.$option1_select.'>option 1</option>
<option value="option2" '.$option2_select.'>option 2</option>
<option value="option3" '.$option3_select.'>option 3</option>
</select>';
echo $select_box;
Refactorings
No refactoring yet !
The Disintegrator
November 28, 2007, November 28, 2007 08:58, permalink
This is the one I use
$proveedores = consulta("SELECT * FROM proveedores ORDER BY Nombre");
while ($fila = mysql_fetch_assoc($proveedores))
$proveedores_list[$fila['id']]= $fila['Nombre'];
mysql_free_result($proveedores);
$proveedores_select = "<select name=\"provID\" id=\"provID\">\n\r<option value=\"\"></option>\n\r";
foreach ($proveedores_list as $key => $value)
{
if($art['provID']==$key)
$proveedores_select .= "<option value=\"$key\" selected=\"selected\">$value</option>\n\r";
else
$proveedores_select .= "<option value=\"$key\">$value</option>\n\r";
}
$proveedores_select .= "</select>\n\r";
techietim
November 28, 2007, November 28, 2007 10:51, permalink
This should do it.
<?php
echo '<select name="options">';
foreach(array("option1", "option2", "option3") as $i){
$select = ($_GET['options'] == $i) ? ' selected="selected"':'';
echo '<option value="'.$i.'"'.$select.'>'.$i.'</option>';
}
echo '</select>';
Daniel
June 28, 2008, June 28, 2008 04:08, permalink
Not sure if you've figured it out by now... or maybe got it from somewhere else? But you can do this:
<?php
$selectedState = $_GET["state"]; // (your $_GET should be santized)
$states = array(
"AL" => "Alabama",
"AK" => "Alaska",
"AZ" => "Arizona",
"AR" => "Arkansas",
"CA" => "California",
etc...
);
$stateSelect = '<select>';
foreach ($states as $key => $value) {
$selected = ($key == $selectedState) ? ' selected="selected"' : '';
$stateSelect .= '<option value="' . $key . '"' . $selected . '>' . $value . '</option>';
}
$stateSelect .= '</select>';
echo $stateSelect;
?>
is there any way to shorten this?... im guessing id be pretty inconvenient if the select box had all fifty states... the thing is, i need it to end up as one variable, which in this case is $select_box