Eduardo Fuerte
asked on
How could a combobox to be started with a defined option dinamically marked?
Hi Experts!
How could a combobox to be started with a defined option dinamically marked?
(depending on the case, the combobox options are not fixed)
Accordingly with the example bellow if I have a value ($d_cr) previously defined to start presenting, how could be the combobox "forced" to present it instead of a blank value?
Thanks in advance!
How could a combobox to be started with a defined option dinamically marked?
(depending on the case, the combobox options are not fixed)
Accordingly with the example bellow if I have a value ($d_cr) previously defined to start presenting, how could be the combobox "forced" to present it instead of a blank value?
CR (L):
<select name="sb_cr">
<!--option selected="selected"-->
// Just try it...
<option selected="<?php echo $d_cr ?>">
</option>
<?php
//----------Inicio Combo 1 (CR) -----------------------------------------------------------------
$sql = mysql_query("select sb_cr, cr_info, substr(descricao,1,25) as descricao from cr where tipo=1 order by descricao");
//----------Final Combo 1-------------------------------------------------------------------------
while ($row = mysql_fetch_array($sql)) {
$id = $row['sb_cr'];
$data = $row['descricao'];
echo '<option value="' . $id . '">' . $data . '</option>';
}
?>
</select>
Thanks in advance!
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Assuming you want a SELECT OPTION to be pre-selected based on the value of a variable, something like this will achieve what you need:
<select>
<?php
while ($row = mysql_fetch_array($sql)) {
printf("<option value='%s' %s>%s</option>", $row['sb_cr'], ($row['sb_cr'] == $d_cr) ? "selected": "", $row['descricao'] );
}
?>
</select>
It outputs a formatted string, and includes a ternary if statement to decide whether to output 'selected'
ASKER
Works correctly.
//----------Inicio Combo 1 (CR) --------------------------
$sql = mysql_query("select sb_cr, cr_info, substr(descricao,1,25) as descricao from cr where tipo=1 order by descricao");
//----------Final Combo 1-------------------------
while ($row = mysql_fetch_array($sql)) {
$id = $row['sb_cr'];
$data = $row['descricao'];
$selected = (($id == $d_cr) ? " selected" : "");
echo '<option value="' . $id . '"' . $selected . '>' . $data . '</option>';
}