使用PHP检查具有多个答案的复选框问题是否正确?

时间:2019-10-29 13:34:42

标签: javascript php html forms

我有一个html表单,其中包含一个复选框问题,正确的答案是选中两个特定的复选框。我想使用PHP检查用户是否具有正确的答案,并将分数变量加1(我知道如何做分数部分,但不知道如何检查他们的答案是否正确。)我该怎么做? / p>

这是复选框问题的HTML,正确的答案是文本和图像。:

<label >What was Mosiac capable of displaying together?:
<input type="checkbox" name="question3" id="q3answer1" value ="answer1" checked="checked" />Videos
<input type="checkbox" name="question3" id="q3answer2" value ="answer2" />Text
<input type="checkbox" name="question3" id="q3answer3" value ="answer3" />Images</label>

1 个答案:

答案 0 :(得分:0)

由于您同时标记了PHP和JavaScript,因此我将提供两种语言的解决方案。我将从JavaScript开始:

let correct = 0;
function submitAnswer() {
   if (document.getElementById("q3answer1").checked == false && 
       document.getElementById("q3answer2").checked == true && 
       document.getElementById("q3answer3").checked == true)
   {
     correct++;
     alert("Correct!");
   }
}
<label>What was Mosaic capable of displaying together?</label>
<input type="checkbox" name="question3" id="q3answer1" value="answer1" checked="checked" />Videos
<input type="checkbox" name="question3" id="q3answer2" value="answer2" />Text
<input type="checkbox" name="question3" id="q3answer3" value="answer3" />Images
<button onclick="submitAnswer()">Submit</button>

现在适用于PHP。首先,由于每个复选框具有相同的name属性,因此必须将name属性分配为数组。接下来,您要做的就是通过查看每个复选框的POST请求是否已设置来查看复选框是否被选中,确保索引1和2被选中,因为它们分别是第二和第三复选框,同时还要确保第一个复选框未选中。以下代码在http://phpfiddle.org上为我工作:

<form method="post">
   <label>What was Mosaic capable of displaying together?</label>
   <input type="checkbox" name="question3[0]" id="q3answer1" value="answer1" checked="checked" />Videos
   <input type="checkbox" name="question3[1]" id="q3answer2" value="answer2" />Text
   <input type="checkbox" name="question3[2]" id="q3answer3" value="answer3" />Images
   <button name="submitBtn">Submit</button>
</form>
<?php
  $correct = 0;
  if (isset($_POST['submitBtn']))
  {
      $checkedBoxes = $_POST['question3'];
      if (!empty($checkedBoxes))
      {
         if (!isset($checkedBoxes[0]) && isset($checkedBoxes[1]) && isset($checkedBoxes[2]))
         {
             $correct++;
             echo "<h3>Correct!</h3>";
         }
      }
      else
      {
         echo "<h3>Please select a checkbox.</h3>";
      }
  }
?>