Roberto C Roberto C - 4 months ago 16
HTML Question

set select <option> as selected in form

I have a form wich inserts some data in a mysql database.
This form contain a select and some options with their respective values like

<select name="car_type">
<option value="sport">Sports car</option>
<option value="van">Van</option>
<option value="large">Large family sedan</option>
<option value="small">Small city car</option>

The form can also be used to update a car's details in the database, it does so by loading the values from the database and fills the form automatically but I am stuck at making the
in the select, selected by default based on the value already set in the DB.
So if the user chooses to edit a car, lets say a car that already has Sports type filled in the DB, I want the form to automatically set the
<option value="sport">Sports car</option>
as selected,
<option selected="selected" value="sport">Sports car</option>
. By not doing this, the user has to choose again the type every time he submits the form, otherwise the first
and its value (sport) is sent by POST.

I am able to retrieve the value from the database by using $data['type'] but I did not find the exact php code to set the selected
to that in the database, can you guys help ?


Although the code looks messy, you can do something like this:

<select name="car_type">
   <option value="sport" <?php if($data['type']=='sport') echo "selected='selected'"; ?> >Sports car</option>
   <option value="van" <?php if($data['type']=='van') echo "selected='selected'"; ?>>Van</option>
   <option value="large" <?php if($data['type']=='large') echo "selected='selected'"; ?>>Large family sedan</option>
   <option value="small" <?php if($data['type']=='small') echo "selected='selected'"; ?>>Small city car</option>