I want to select a target country in html.
And this code should return for example “Turkey” from my db.
<?php echo $_SESSION['user']['www']?>
I have a country list, and I use it here in settings_myinfo.php
:
<select id="profile-country" name="profile_country"> <option value="Select your Country">Select your Country</option> <?php include($root."countries_optionlist.php");?> </select>
countries_optionlist.php
:
<option value="Afganistan">Afghanistan</option> <option value="Albania">Albania</option> <option value="Algeria">Algeria</option> <option value="American Samoa">American Samoa</option> <option value="Andorra">Andorra</option> <option value="Angola">Angola</option> <option value="Anguilla">Anguilla</option> <option value="Antigua & Barbuda">Antigua & Barbuda</option> <option value="Argentina">Argentina</option> <option value="Armenia">Armenia</option> <option value="Aruba">Aruba</option> <option value="Australia">Australia</option> <option value="Austria">Austria</option> <option value="Azerbaijan">Azerbaijan</option> <option value="Bahamas">Bahamas</option> <option value="Bahrain">Bahrain</option> <option value="Bangladesh">Bangladesh</option> <option value="Barbados">Barbados</option> and more...
I want to add selected tag to target country like this:
<option value="Turkey" selected>Turkey</option>
I did some research on Google and StackOverflow but I couldn’t find any solution. Could you provide me with a suggestion on how to achieve this?
Advertisement
Answer
In each option, you can check if the session variable matches that country and add the selected
attribute.
<?php $user_country = $_SESSION['user']['www']; ?> <option value="Afganistan" <?php if ($user_country == 'Afghanistan') echo 'selected'; ?>>Afghanistan</option> <option value="Albania" <?php if ($user_country == 'Albania') echo 'selected'; ?>>Albania</option> <option value="Algeria" <?php if ($user_country == 'Algeria') echo 'selected'; ?>>Algeria</option> ...
You can simplify this by putting all the country names in an array. Then you can loop like this:
<?php $user_country = $_SESSION['user']['www']; foreach ($countries as $country) { ?> <option value="<?php echo $country; ?>" <?php if ($user_country == $country) echo 'selected'; ?>> <?php echo htmlspecialchars($country); ?> </option> <?php }