douzhuo5671 2018-07-19 21:20
浏览 98
已采纳

PHP如果变量等于下拉列表中的值,则将“selected”属性添加到选项中

I have a drop down menu that checks whether a user has already selected a value by checking database and if they have, I want to add a 'selected' attribute to that option so that when they edit their profile, that option is preselected by what they chose.

Heres an example of what I am trying to accomplish. It works for text inputs but I don't know how to do it with dropdown lists.

So if user selects 'Dog', it gets place in database and adds 'selected' as attribute

$animal = $mysqli->escape_string($_POST['animal']);
//PHP UPDATE database script -------->

<label>Animal</label></br>
    <select name='animal' value='<?php if($animal == value){ /*Add selected attribute to option */ ?>'>
         <option value="" disabled selected>Select One</option>
         <option value="" disabled>----------------</option>
         <option value="Dog">Dog</option>
         <option value="Cat">Cat</option>
         <option value="Bird">Bird</option>  
    </select>
  • 写回答

2条回答 默认 最新

  • duanluwei9374 2018-07-19 21:48
    关注

    Define an array of options

    $animals = ['Dog', 'Cat', 'Bird'];
    

    Then generate the list of options for the <select> from that array, checking the selected animal against each one. If it matches, then add the selected attribute.

    <label>Animal</label></br>
    <select name='animal'>
         <!-- select the default if none of the options are selected -->
         <option value="" disabled <?php if (!in_array($animal, $animals)) echo 'selected' ?>>
             Select One
         </option>
         <option value="" disabled>----------------</option>
         <?php foreach ($animals as $option) {
            echo "<option ";
            if ($animal == $option) {
                echo 'selected';
            }
            echo ">$option</option>"; 
         ?>
    </select>
    

    value attributes aren't required for your <option> elements in this case, since you're using the same values for the option text. (If the value attribute is omitted, the option text will be used as the value.)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器