当不在表单中时,只能使用PHP选择一个单选按钮

时间:2013-02-19 22:03:40

标签: php radio-button

我一直在为学校开展这个项目,我们制作了一个迷你课程网站,根据我们选择的主题对用户进行测验。问题,选择和答案必须都在一个数组中,然后可以显示为问题和单选按钮选择。我达到了这一点,我现在只在一个工作,直到我完成它。我现在遇到的问题是所有的单选按钮都是可选的。我怎么能这样做,以便每个问题只能选择一个单选按钮?

这是我的代码:

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>Untitled Document</title>
    </head>

    <body>
    <?php
$score = 0;

    //multi-dimensional arrays for questions, selections, and answers
    $questions = array(
    array('question' => 'Which is optional to making Easy Fudge?', 
        'choice 1' => 'Nuts', 
        'choice 2' => 'Condensed Milk', 
        'choice 3' => 'semi-sweet morsels', 
        'choice 4' => 'bakers chocolate', 
        'answer' => 'nuts'),
        );

    //looping through the questions with nested loops
    foreach($questions as $question){
echo $question['question'] . '<br />';  
echo '<input type="radio" name = "nuts" value="nuts" id="nuts"> ' . $question['choice 1'] . '<br />';   
echo '<input type="radio" name = "condensed milk" value="condensed milk" id="condensed milk"> ' . $question['choice 2'] . '<br />';
echo '<input type="radio" name = "semi-sweet morsels" value="semi-sweet morsels" id="semi-sweet morsels"> ' . $question['choice 3'] . '<br />';
echo '<input type="radio" name = "bakers chocolate" value="bakers chocolate" id="backers chocolate"> ' . $question['choice 4'] . '<br />';  
    }

    ?>
    </body>
    </html>

1 个答案:

答案 0 :(得分:1)

为所有相关的单选按钮指定相同的名称。例如:

foreach($questions as $question){
    echo $question['question'] . '<br />';  
    echo '<input type="radio" name = "nuts" value="nuts" id="nuts"> ' . $question['choice 1'] . '<br />';   
    echo '<input type="radio" name = "nuts" value="condensed milk" id="condensed_milk"> ' . $question['choice 2'] . '<br />';
    echo '<input type="radio" name = "nuts" value="semi-sweet morsels" id="semi-sweet_morsels"> ' . $question['choice 3'] . '<br />';
    echo '<input type="radio" name = "nuts" value="bakers chocolate" id="backers_chocolate"> ' . $question['choice 4'] . '<br />';  
}

作为进一步说明..有效的Id属性不能包含空格,因此在上面的示例中,我已使用下划线替换了您的空格。