Dookoto_Sea
Dookoto_Sea

Reputation: 549

Building a simple quiz in HTML using JavaScript

I am new to HTML and JavaScript and I am trying to write the function solution that will return a integer score verifying how many check-boxes selected by the user are correct. The function should_be_checked(question_index, choice_index) is already defined which returns true if the answer is correct or else returns false. I want to use the function should_be_checked inside my solution function to evaluate the score. How do I get the input values in an array from the HTML form and then generate the score using the array values against the correct values from the should_be_checked function. For example: If i do should_be_checked(2, 2) it will return true as it is the right answer. question_index and choice_index are the values passed as argument to should_be_checked function. The solution() function will be called on a button click once the user selects the check-boxes.

function solution() {
  var score = 0;
  $("input[type=checkbox]").each(checkbox => {
      let args = checkbox.attr("id").split("-"); // Split at the dashes to get an array containing ["choice", "1", "2"]
      args.shift() // Remove the first element that says "choice"
      if (checkbox.prop("checked") !== should_be_checked(...args)) {
        score = score + 1; // Increment the score
      });
    return score;
  }
<form>
  <fieldset id="question-1">
    <legend>Easy question</legend>
    <input type="checkbox" id="choice-1-1" checked>Incorrect answer</input>
  </fieldset>
  <fieldset id="question-2">
    <legend>Another sample question</legend>
    <input type="checkbox" id="choice-2-1">Sample incorrect answer</input><br>
    <input type="checkbox" id="choice-2-2" checked="checked">Sample correct answer</input>
  </fieldset>
</form>

Upvotes: -1

Views: 959

Answers (1)

pfg
pfg

Reputation: 3577

If you loop over each checkbox you can check if they should be checked using your function

let allQuestionsCorrect = true;
$("input[type=checkbox]").each(checkbox => {
  let args = checkbox.attr("id").split("-"); // Split at the dashes to get an array containing ["choice", "1", "2"]
  args.shift() // Remove the first element that says "choice"
  if(checkbox.prop("checked") !== should_be_checked(...args)) {
    allQuestionsCorrect = false; // If it shouldn't be checked and it is or should be checked and it isn't, the questions are not all correct
  }
});
return allQuestionsCorrect

Then if their checked property isn't what it should be return false

Upvotes: 2

Related Questions