将下拉列表的索引设置为值

时间:2014-05-16 16:04:21

标签: php html drop-down-menu

我有一个下拉列表

   <label for="staffType">Staff Type<br /></label>
      <select id="myList" name="staffType" onchange="show()">
        <option>Care Staff</option>
        <option>Nursing Staff</option>
        <option>Administrator</option>
      </select>

我想将索引设置为$ user ['staffType']。

最好的方法是什么? 用于创建用户对象的php代码

<?php while ($cursor->hasNext()):
$user = $cursor->getNext(); ?>

1 个答案:

答案 0 :(得分:1)

根据您设置下拉值的方式,您需要给出一个条件来设置相应的值是否匹配,如果是,则将其设置为selected。考虑这个例子:

// from db values
$values_from_db = array(
    array('id' => 1, 'staffType' => 'Care Staff'),
    array('id' => 2, 'staffType' => 'Nursing Staff'),
    array('id' => 3, 'staffType' => 'Administrator'),
);

// current value to be checked
$user['staffType'] = 'Administrator';

// i don't know how your select box values are rendered
<label for="staffType">Staff Type<br /></label>
<select id="myList" name="staffType" onchange="show()">
<?php foreach($values_from_db as $key => $value): ?>
    <option <?php echo ($value['staffType'] == $user['staffType']) ? 'selected': ''; ?> ><?php echo $value['staffType']; ?></option>
<?php endforeach; ?>
</select>