dongpu42006096 2015-07-16 20:26
浏览 58
已采纳

选择列表数组 - 将选项预填充到数组顶部

I am printing a simple select list out by looping through an associative array which is populated elsewhere.

<select id="choice" name="choice">
    <?php 
    foreach ($this->choice as $key => $value) { 
    echo "<option name=".$value." value=".$key.">" .$value. "</option>" ; 
    } 
    ?>
</select>

This select list gives the options available from the array. However, I am trying to pre-populate the list with the selected value, for example if a user is updating their user information, then I would like to set that choice at the top of the list (ideally without the choice appearing further down the list).

I have access to this data in a variable which I have queried:

$this->selected_choice //value
$this->selected_id //key

Now I have been testing some solutions

<select id="choice" name="choice">
    <option name="<?php echo $this->selected_choice; ?>" value="<?php echo $this->selected_id;?>">"<?php echo $this->selected_choice; ?></option>
    <?php 
    foreach ($this->choice as $key => $value) { 
    echo "<option name=".$value." value=".$key.">" .$value. "</option>" ; 
    } 
    ?>
</select>

This solution does display the users choice on top of the list, but the foreach loop will also display this option as there is no indication that it shouldn't.

This is my question to you guys, how can I do this so the the selected_choice appears at the top of the list, but will then not appear in the foreach array.

I am hoping there is some simple solution to this problem, as it is not so important, but something I come across quite a lot.

  • 写回答

1条回答 默认 最新

  • dpl3350 2015-07-16 20:28
    关注

    Option have no "name". Name is attribute for SELECT tag. If option is selected, you need to pass "selected" attribute in body of option Ex: <option value="1" selected>Tramtada</option>

    Do it this way:

      <select id="choice" name="choice">
        <?php 
          foreach ($this->choice as $key => $value) { 
            echo "<option <?php if($key == $this->selected_id) {?> selected <?php } ?> value=".$key.">" .$value. "</option>" ; 
          } 
        ?>
      </select>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算