Roberto C
Roberto C

Reputation: 301

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>
</select>

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 <option> 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 <option> 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 <option> to that in the database, can you guys help ?

Upvotes: 1

Views: 896

Answers (3)

Fyntasia
Fyntasia

Reputation: 1143

If you're trying to mark the active car type I would do it like this:

foreach ($car_types as $car_type){
    echo '<option value="'.$car_type.'" '.($data['type']==$car_type?'selected':'').'>'.$car_type.'</option>';
}

Upvotes: 0

Paul Lo
Paul Lo

Reputation: 6138

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>
</select>

Upvotes: 1

Dave
Dave

Reputation: 3288

<option value="large" <?php echo ($dbvalue=="large") ? "selected=\"selected\"" : "" ;?>>Large family sedan</option>

Work out the sql query bit yourself and replace my $dbvalue with the column data from your db

Upvotes: 0

Related Questions