black black - 2 months ago 30
PHP Question

display selected value in dropdown php after clicking submit button

I need help. I have try a lot of things but still didnt get the solution for it. I want to display back the selected value for dropdown list after the user click the submit button, but everything I tries I only display either the first or last value of the dropdown element. Im using d..while looping to call out the option value for the dropdown list. Here a my code:

<p align="center">Class
<select name="class_code" size="1" id="class_code">

<?php
do{?>
<option value="<?php echo $row_class_code['class_code']?>" $selected><?php echo $row_class_code['class_code']?></option>
<?php
} while ($row_class_code = mysql_fetch_assoc($class_code));
$rows = mysql_num_rows($class_code);
if($rows > 0) {
mysql_data_seek($class_code, 0);
$row_class_code = mysql_fetch_assoc($class_code);
}?>
</select>

<input type="submit" name="submit" id="submit" value="Proceed" />
</p>


Please, can someone help me.

Answer

Presumably when submitting you have the selected value in $_POST['class_code'] - so add a condition to check and add the selected attribute for options that match it:

<select name="class_code" size="1" id="class_code">
    <?php
    do {
        $selected = (isset($_POST['class_code']) && $row_class_code['class_code'] == $_POST['class_code']);
        ?>
        <option value="<?php echo $row_class_code['class_code']?>"<?php if ($selected) { echo ' selected="selected"'; } ?>><?php echo $row_class_code['class_code']?></option>
        <?php
    } while ($row_class_code = mysql_fetch_assoc($class_code));
    $rows = mysql_num_rows($class_code);
    if ($rows > 0) {
        mysql_data_seek($class_code, 0);
        $row_class_code = mysql_fetch_assoc($class_code);
    }
    ?>
</select>
Comments