简体   繁体   中英

How to display selected value in country dropdown list

I'm trying to display the nationality of an employee from the database into the dropdown, which contains all country names. I had a separate page to store the country list and included it in the edit page.

edit.php:

 <div class="form-group" id="selected_country">
   <label>Nationality</label>
   <?php include ('country.php');?>
 </div>

country.php:

<select class="form-control"id="country" name="country">
  <option> Select country</option>
  <option value="Afghanistan">Afghanistan</option>
  <option value="Åland Islands">Åland Islands</option>
  <option value="Zimbabwe">Zimbabwe</option>
</select>

I've done a similar code for another field that has only two values in the dropdown but I'm not familiar with this long list. Pls, do help me.

This is what I have experience in. I've added this just for reference. Can I do something like this to the above problem as well or there is some other way?

  <div class="form-group">
    <label>Status</label>
    <select name="emp_edit_status" class="form-control">
      <option value="Active"<?php if($rowEdit['emp_status'] == 'Active') { ?> 
         selected="selected"<?php } ?>> Active</option>
      
      <option value="Inactive" <?php if($rowEdit['emp_status'] == 'Inactive') { 
        ?> selected="selected"<?php } ?>> Inactive</option>

    </select>
   </div>

You're on the right lines, but your code will become rather heavy if you type out each <option> line in full.

I'd go for something like this:

// Dummy data. substitute whatever you have for employee data in the 
// foreach loop below
$employee = ['country'=>'United Kingdom'];

$countryList = ["Afghanistan", "Mexico", "New Zealand", "United Kingdom", "United States","Zimbabwe"];

echo '<select name="country">';
echo "<option value='' >Select Country</option>";


foreach($countryList as $country) {
    $sel = ($employee['country'] === $country) ? 'selected' : '';
    echo "<option value='$country' $sel>$country</option>";
}
echo '</select>';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM