如何设置<select>标签</select>的值

时间:2010-06-29 05:19:46

标签: php

使用Php我写了下拉列表框代码。 编辑员工详细信息我使用了相同的代码,我尝试在列表框中设置值,但未设置值。怎么做。

Employee Name: <select name=emp_name *$value='$name'*>
<option> -- EMPLOYEE NAME -- </option>
<?  
    while ($q->fetchInto($row)){
        print "<option>$row[0]</option>";
    }
?>
</select>

4 个答案:

答案 0 :(得分:4)

在构建选项时,您必须将所选选项设置为选中:

<select name='emp_name'>
  <?
    //Define the array of possible options.
    //This can come from the database fetch such as:
    $options = $q->fetchMutipleVals();
    //Or defined manually such as:
    $options = array('value1'=>'label1', 'value2'=>'label2'); //etc.
    foreach ($options as $val => $label){
      $selected = ($name == $val)? "selected='selected'":''; //sets html flag
      echo "<option value='$val' $selected>$label</option>\n";
    }
  ?>
 </select>

答案 1 :(得分:2)

在迭代时测试正确的值,并使用<option>属性将selected='selected'标记为所选值:

Employee Name: <select name="emp_name">
<option> -- EMPLOYEE NAME -- </option>
<?php
    while ($q->fetchInto($row)){
        if($row[0] == $name){
           $selected_text = " selected='selected'";
        }else{
           $selected_text = "";
        }
        print "<option{$selected_text}>{$row[0]}</option>";
    }
?>
</select>

答案 2 :(得分:1)

您需要选择的option代码具有selected属性:

<select>
  <option> -- EMPLOYEE NAME -- </option>
  <option>Sally</option>
  <option selected="selected">Fred</option>
  <option>Liz</option>
</select>

答案 3 :(得分:0)

尝试

Employee Name: < select name=emp_name $value='$name' > <    option > -- EMPLOYEE NAME -- < / option >

< ? while ($q->fetchInto($row))

{ print "<option>$row[0]</option>"; } < / select >

? >
相关问题