Pippa Rose Smith
Pippa Rose Smith

Reputation: 1416

Select an option in a select box, given the option in word form in a PHP form

I have a standard select box in my php form for my website containing a list of counties in the UK, an example of which is shown below:

<p class='form_title'>County<br>
    <select id="county" name="county">
        <optgroup label="England">
            <option>Bedfordshire</option>
            <option>Berkshire</option>
            <option>Bristol</option>

            ....

            <option>Wiltshire</option>
            <option>Worcestershire</option>
        </optgroup>

        <optgroup label="Wales">
            <option>Anglesey</option>

            ...

            <option>Radnorshire</option>
        </optgroup>

        <optgroup label="Scotland">
            <option>Aberdeenshire</option>

            ...

            <option>Wigtownshire</option>
        </optgroup>

        <optgroup label="Northern Ireland">
            <option>Antrim</option>

            ...

            <option>Tyrone</option>
        </optgroup>
    </select>
</p>

Once a user has submitted details, they can then edit them.

I therefore need a way to have selected the option that they previously chose, given that I have the option they chose saved in word form, such as Bedfordshire.

I know I need to add the word selected to one of the options, but I was wondering if there was a better way to do it than a massive case statement.

Thanks

Upvotes: 0

Views: 149

Answers (2)

Mihai Iorga
Mihai Iorga

Reputation: 39704

You should set an option value for each option to track the value.

Also you should be generating that from a database and then you can set selected based on a $_GET or $_POST:

for example:

foreach($county as $name){
    $selected = '';
    if($name == $_GET['name']){
        $selected = ' selected="selected"';
    }
    echo '<option value="'.$name.'"'.$selected.'>'.$name.'</option>';
}

this doesn't include your optgroup but that also should come from database.

Upvotes: 1

Manatok
Manatok

Reputation: 5706

Try something like this:

  foreach($places as $place) {
      $selected = $prevSelectionId == $place['id'] ? " selected='selected' " : "";
      echo "<option $selected value='".$place['id']."'>".$place['name']."</option>";
  }
 </select>

Upvotes: 1

Related Questions