首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >PHP、HTML、Javascript -从foreach循环创建交互式下拉菜单

PHP、HTML、Javascript -从foreach循环创建交互式下拉菜单
EN

Stack Overflow用户
提问于 2018-02-02 05:50:57
回答 1查看 79关注 0票数 0

我正在做一个投票页面,在那里用户可以投票在几个投票,其中有不同的答案取决于类别。要保持简单,请执行以下操作:

代码说明

我有两个foreach循环:第一个循环遍历所有的投票,并将它们打印出来。第二个迭代遍历调查的所有可用答案。从category_id收到多个应答。答案打印在每个民意测验下面。它目前的显示方式是,每个民意调查及其相应的答案都打印在彼此的下方,有点像一个列表。

我想要的是

我想有一个下拉菜单,其中显示所有可用投票时被点击。当点击投票时,它必须显示投票本身和相应的答案。

代码

代码语言:javascript
复制
<!-- Voting form --> 
<h3> Pollpagina </h3>
<?php
    //prepare statement to select all polls
    $get_polls = $db->prepare('SELECT * FROM polls');
    $get_polls->execute();
    $all_polls = $get_polls->fetchAll();
    //treat every poll as an individual poll
    foreach($all_polls as $single_poll) {
?>  
        <!-- Create a form for each poll, with the corresponding answers as radio buttons -->
        <form method="post" action="">
            <div class="poll">
<?php
                //get textual poll and its corresponding id and category
                $poll_id = $single_poll['id'];
                $poll = $single_poll['poll'];
                $category = $single_poll['category_id'];
                //echo each poll
                echo $poll, "<br>";
                //prepare statement for getting all the answers from a specific category
                $category_answers = $db->prepare('SELECT answer FROM answers WHERE category_id = ?');
                $category_answers->bindValue(1, $category, PDO::PARAM_STR);
                $category_answers->execute();
                $all_answers = $category_answers->fetchAll();
                //create a radio button for each answer
                foreach($all_answers as $single_array_answer) {
                    $single_answer = array_shift($single_array_answer);
?>
                    <input type="radio" name="radio" value="<?php print_r($single_answer); ?>"> <?php print_r($single_answer); ?>  <br>
<?php
                }
?>
                <!-- If a vote has been submitted, the value tag will send the corresponding poll id -->
                <button type="submit" name="submit" value="<?php print_r($poll_id); ?>"</button>Submit
            </div>
        </form>
<?php
    }
?>
EN

回答 1

Stack Overflow用户

发布于 2018-02-02 06:05:19

要显示投票,请执行以下操作:

代码语言:javascript
复制
<select id="dropdown">
   <?php
     echo "<option value='$pollId'>$pollName</option>";
   ?>
</select>

要显示所有调查答案,请使用jquery:

代码语言:javascript
复制
$("#dropdown").on("change",function){
  <?php
   /*
      print all poll answers here 
   */
?>;
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48572309

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档