[英]PHP Country Option list adding “select” tag with checking String value?
I want to select a target country in html.我想 select 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
:我有一个国家/地区列表,我在
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
: 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.我对 Google 和 StackOverflow 进行了一些研究,但找不到任何解决方案。 Could you provide me with a suggestion on how to achieve this?
你能给我一个关于如何实现这一目标的建议吗?
In each option, you can check if the session variable matches that country and add the selected
attribute.在每个选项中,您可以检查 session 变量是否与该国家/地区匹配并添加
selected
属性。
<?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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.