Link to home
Start Free TrialLog in
Avatar of Eduardo Fuerte
Eduardo FuerteFlag for Brazil

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?


                 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>

Open in new window


Thanks in advance!
ASKER CERTIFIED SOLUTION
Avatar of Ray Paseur
Ray Paseur
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of gr8gonzo
<?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'];
        $selected = (($id == $d_cr) ? " selected" : "");
        echo '<option value="' . $id . '"' . $selected . '>' . $data . '</option>';
    }
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>

Open in new window

It outputs a formatted string, and includes a ternary if statement to decide whether to output 'selected'
Avatar of Eduardo Fuerte

ASKER

Works correctly.