Slothalicious Slothalicious - 1 year ago 85
PHP Question

How to keep PHP dropdown selection on refresh inside a form?

I want to keep the current selection in the dropdown when you submit the form. How do I do that?

My code:

echo '<select name="RoomSelection">';
while ($row = mysqli_fetch_array($selectroom1)) {
echo '<option value="'.$row['Location'].'">'.$row['Location'].'</option>';
}
echo '</select>';

Answer Source

It's easy:

echo '<select name="RoomSelection">';
while ($row = mysqli_fetch_array($selectroom1)) {
    echo '<option value="'.$row['Location'].'";
    if($_POST['RoomSelection']==$row['Location']) echo ' SELECTED '; 
    echo '>'.$row['Location'].'</option>';
}
echo '</select>';

You just write SELECTED if the value is igual to the post value ... if your form is in method POST, you must adapt it if it's in GET.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download