如何在PHP的下拉列表中放置默认值?

时间:2013-09-24 14:13:07

标签: php drop-down-menu

我的代码如下:

<select autofocus="autofocus" name="SourceCountry" id="SourceCountry">
  <?php populate_country();?>
  </select>

我在该下拉列表中填充了世界上所有国家。我想要一个特定的国家名称(比如日本)作为默认选择。我不确定select标签的哪个属性或属性可以做到这一点。试图使用很多,但没有成功。有人可以建议吗?

populate_country的代码如下:

if(connect_to_DB()==1)
    $result=FetchCountriesList();
    //mysqli_data_seek($result,0);
    while($row = mysqli_fetch_assoc($result))
    {       
        echo '<option value='.$row['CountryName'].'>'.$row['CountryName'].'</option>';
     }

在FetchCountriesList()中,有一个选择查询,如:

从国家/地区选择不同的CountryName

由于

6 个答案:

答案 0 :(得分:1)

编辑你的功能并尝试找到日本并将其设置为选中:)

if(connect_to_DB()==1) $result=FetchCountriesList(); 
//mysqli_data_seek($result,0);
while($row = mysqli_fetch_assoc($result)) {
    if($row['CountryName'] !== "Japan") {
        echo '<option value='.$row['CountryName'].'>'.$row['CountryName'].'</option>';
    } else {
        echo '<option value='.$row['CountryName'].' selected="selected">'.$row['CountryName'].'</option>';
    }
}

答案 1 :(得分:0)

只需在您希望选择的选项值上添加属性selected="selected"

例如:

<option value="Japan" selected="selected">Japan</option>

要在您的功能中使用此功能,请将此功能替换为:

function populate_country($selected = NULL) {

    if(connect_to_DB()==1) $result=FetchCountriesList(); 

    //mysqli_data_seek($result,0); 

    while($row = mysqli_fetch_assoc($result)) { 

        echo '<option value="'.$row['CountryName'].'" '.($selected == $row['CountryName'] ? 'selected="selected"' : NULL).'>'.$row['CountryName'].'</option>';

    }

}

然后您可以在HTML中使用它:

<select autofocus="autofocus" name="SourceCountry" id="SourceCountry">
  <?php populate_country("Japan");?>
  </select>

答案 2 :(得分:0)

添加seleteced属性,例如:

<option value="test" selected="selected">Bla</option>


$defValue = 'Japan';
while($row = mysqli_fetch_assoc($result)) {
  echo '<option value="' . $row['CountryName'] . '"';
  if ($row['CountryName'] === $defValue) {
    echo ' selected="selected"';
  }
  echo '>';
  echo $row['CountryName'] . '</option>';
}

答案 3 :(得分:0)

添加属性selected。试试这个:

<select name="country">
    <option value="kor">Korea</option>
    <option value="rus">Russia</option>
    <option selected="selected" value="jap">Japan</option>
</select>

答案 4 :(得分:0)

在函数populate_country()中为您的选项添加所选内容。 (在您希望仅选择默认选项中)

答案 5 :(得分:0)

<select>
    <option> Red </option>
    <option selected="selected"> blue </option>
    <option> yellow </option>
</select>

蓝色将在该下拉列表中被选中。

基本上你需要循环遍历你的值并匹配你想要的值与你拥有的值匹配,并将selected="selected"字符串添加到该选项中:

我会这样做:(未经测试)

function populate_country($country){
    $countries = array('algeria', 'japan', 'mexico', 'united kingdom' ..... );
    foreach($countries as $country){
        $selected = (strtolower($selected) == $country) ? ' selected="selected"' : null;
        echo "<option$selected>".ucwords($country)."</option>\r\n";
    }
}