dqq46733 2019-01-25 01:09
浏览 114
已采纳

使用PHP将HTML复选框列表更改为选择下拉列表

I am trying to create a html/php form that allows an array of data to be displayed in a drop/selection menu. How would i turn this into one?

<?php

$OptionID   =   1;

foreach( $this->setRoleOptions as $RoleID => $RoleName ) :

    echo '<div align="center">';
    echo '<input type="checkbox" style="width: 30px;" name="RoleID" value="'. $RoleID .'" ';

    if ( $OptionID == 1 ) :

        echo ' CHECKED ';

    endif;

    echo '/>&nbsp;'. $RoleName;
    echo '</div>';

    ++$OptionID; 

endforeach;

?>

I have tried the below code which gets the array but once the option is selected, nothing happens.

<?php
$OptionID = array("Administrative", "Operations 1", "Operations 2");
?>

<select>
    <?php foreach ($this->setRoleOptions as $RoleID => $RoleName): ?>
    <option name="RoleID" value="<?php echo $RoleID; ?>"<?php if ($row['RoleID'] == $OptionID): ?> selected="selected"<?php endif; ?>>
        <?php echo $RoleName;?>
    </option>
    <?php endforeach; ?>
</select>
  • 写回答

2条回答 默认 最新

  • doucuodan0897 2019-01-25 01:15
    关注

    To translate the checkboxes that you have currently, just create a simple <select> markup using the same data that you have.

    Here's the idea:

    <?php $OptionID = array("Administrative", "Operations 1", "Operations 2"); ?>
    
    <select name="RoleID">
        <?php foreach ($this->setRoleOptions as $RoleID => $RoleName): ?>
        <option 
            value="<?php echo $RoleID; ?>" 
            <?php echo in_array($RoleID, $OptionID) ? 'selected: ''; ?>
        >
            <?php echo $RoleName; ?>
        </option>
        <?php endforeach; ?>
    </select>
    

    The name attribute should be on the select tag itself. The value attributes should be on the option tags.

    And since on each iteration, you'd want to check whether the current $RoleID is inside the $OptionID which is an array, it would be better to use the built in function in_array() instead.

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

报告相同问题?

悬赏问题

  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?
  • ¥15 关于#vue.js#的问题:修改用户信息功能图片无法回显,数据库中只存了一张图片(相关搜索:字符串)
  • ¥15 texstudio的问题,