javascript - 在 while 循环中嵌入 Optgroup 的选择组

标签 javascript php

我有一个 while 循环,用于获取 agentspec 表中的所有值并将它们设置为选择字段中的选项。

agentspec 表中的值按 category 字段分组,我想使用 category 字段作为我的 optgroup 标签。

这是我尝试过的。它当前输出所有 category 字段值,后跟所有 spec 值 例如。

Category: Farmer 
Category: Farmer
Category: Farmer
Category: Colour
Category: Colour
Spec: Grain
Spec: Sand
Spec: Fruit
Spec: Red
Spec: Blue

我希望它根据在 category 字段中设置的组来输出 spec 值。

例如。

Category: Farmer 
Spec: Grain
Spec: Sand
Spec: Fruit
Category: Colour 
Spec: Red
Spec: Blue

代码:

$st = DBase::singleton()
            ->prepare(
                'select * ' .
                'from `agentspec` ' .
                'limit 0,30');

    $option = '';
    $optgroup = '';
    if ($st->execute())
    {
           while ($row = $st->fetch(PDO::FETCH_OBJ))
            {
    $id = $row->id;
    $cat = $row->category;
    $spec = htmlspecialchars($row->spec);
    $desc = htmlspecialchars($row->desc);

    $optgroup .=  '<optgroup label= '.$cat.'></optgroup>';
    $option .= '<option value = "agents/'.$id.'/themes">'.$spec.' , '.$desc.'</option>';

    }
    }


    ?>


    <select id="selectbox" name="" class=form-control>
    <option selected="selected">Select a Specialist Area
    </option>
    <?php echo $optgroup;?>
    <?php echo $option;?>

</select>

最佳答案

选项是 optgroup 的子元素,因此您必须执行类似的操作 这个粗fiddle example :

您的代码片段的重写版本:

<?php
        $st = DBase::singleton()
                    ->prepare(
                        'select * ' .
                        'from `agentspec` ' .
                        'limit 0,30');


        $optHtml= '';
        $optgroups = array();

        if ($st->execute())
        {
            while ($row = $st->fetch(PDO::FETCH_OBJ))
            {
                $id = $row->id;
                $cat = $row->category;
                $spec = htmlspecialchars($row->spec);
                $desc = htmlspecialchars($row->desc);
                if (!array_key_exists($cat, $optgroups)) {
                    $optgroups[$cat] = "";
                }
                $optgroups[$cat].='<option value = "agents/'.$id.'/themes">'.$spec.' , '.$desc.'</option>';
            }
            foreach($optgroups as $label=>$optionsHtml) {
                $optHtml.= '<optgroup label="'.$label.'">'.$optionsHtml.'</optgroup>';
            }   
        }


?>

<select id="selectbox" name="" class=form-control>
    <option selected="selected">Select a Specialist Area</option>
    <?php echo $optHtml; ?>
</select>

关于javascript - 在 while 循环中嵌入 Optgroup 的选择组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22093883/

相关文章:

javascript - 我将如何在 vanilla js 中编写这个 JQuery addClass 方法

javascript - 永久显示隐藏的div

javascript - 如何将 accessibilityLabel 添加到 react native app (Android),这样 content-desc 就不会为空

javascript - 如何学习创建日期选择器

php - 如何使用sql查询获得第四高的值

javascript - 如何.abort() 一个ajax 文件上传?

php - 提交表单后仅通过 PHP 刷新 1 DIV

php - 错误未选择数据库 PHP

php - 使用 PHPxcel 减少数据库插入的执行时间

php - 简单的代码不起作用