Correct Jquery test

Viewed 154

I created jquery test with the help of https://codepen.io. The code was working great, but with a different result. I was looking a way where I could display the result with both question and choices, highlighting right(green) and wrong(red). Below is the code I tried like when useranswer matches correctanaswer, then highlight the div in green else red color. Could you let me know where I was going wrong with my code.

test.js

var quiz = [{
    question: "How can you get the type of arguments passed to a function?",
    answers: ["using typeof operator", "using getType function", "Both of the above", "None"],
    correctAnswer: 0
}, {
    question: "Which built-in method returns the character at the specified index?",
    answers: ["characterAt()", "getCharAt()", "charAt()", "None"],
    correctAnswer: 2
}]

var i = 0;
var score = 0;

$(document).ready(function () {
    $('#start').on('click', function () {
        $('#questions').text(quiz[i].question);
        $('#zero').text(quiz[i].answers[0]);
        $('#one').text(quiz[i].answers[1]); 

    });
});

$(document).ready(function () {
    $(document).on('click', '#next', function () {
        var answer = $('input[name="answers"]:checked').val();
        var answerString = quiz[i].answers[answer];
        $('p[class="userAnswer"][value=' + i + ']').text(answerString);
        var correctAnswer = quiz[i].correctAnswer;
        $('p[class="correctAnswer"][value=' + i + ']').text(quiz[i].answers[correctAnswer]);
        if (answer == quiz[i].correctAnswer) {

        } else {
            $('tr[class="row"][name=' + i + ']').css('background', '#FE2E64');
        }


        if (i < 2) {
            $('.choices').css('display', 'none');
            $('#questions').text(quiz[i].question);
            $('#zero').text(quiz[i].answers[0]);
            $('#one').text(quiz[i].answers[1]);
            $('.choices').show('slow');
            $('input[name="answers"]').prop('checked', false);

        }    

    });
});

    
     
2 Answers

To display all answer with correct or wrong you need loop through all question and then see if the answer choose by user and the correctAnswer are same or not depending on that append required html to some variable .Also, whenever user select any answer in below code snippet i have store same in some array so that we can use while checking correct or wrong answer.

Demo Code :

var correctAnswer;
var display_result = "";
var quiz = [{
  question: "How can you get the type of arguments passed to a function?",
  answers: ["using typeof operator", "using getType function", "Both of the above", "None"],
  correctAnswer: 0
}, {
  question: "Which built-in method returns the character at the specified index?",
  answers: ["characterAt()", "getCharAt()", "charAt()", "None"],
  correctAnswer: 2
}]

var i = 0;
var score = 0;

$(document).ready(function() {
  $('#start').on('click', function() {
    $('#questions').text(quiz[i].question);
    $('#zero').text(quiz[i].answers[0]);
    $('#one').text(quiz[i].answers[1]);
    $('#two').text(quiz[i].answers[2]);
    $('#three').text(quiz[i].answers[3]);
    $('#start').hide();
    $('.choices').show('slow');
    $('#next').show('slow');
  });
});
var users_answers = [];
$(document).ready(function() {
  $(document).on('click', '#next', function() {
    var answer = $('input[name="answers"]:checked').val();
    var answerString = quiz[i].answers[answer];
    $('p[class="userAnswer"][value=' + i + ']').text(answerString);
    correctAnswer = quiz[i].correctAnswer;
    $('p[class="correctAnswer"][value=' + i + ']').text(quiz[i].answers[correctAnswer]);
    users_answers.push(answer);
    if (answer == quiz[i].correctAnswer) {
      score++;
    } else {
      $('tr[class="row"][name=' + i + ']').css('background', '#FE2E64');
    }
    if (!$('input[name="answers"]').is(':checked')) {
      alert("please make a choice");
      return undefined; //stops executing the rest of the code
    }
    i++;

    if (i < 2) {
      console.log("in")
      $('.choices').css('display', 'none');
      $('#questions').text(quiz[i].question);
      $('#zero').text(quiz[i].answers[0]);
      $('#one').text(quiz[i].answers[1]);
      $('#two').text(quiz[i].answers[2]);
      $('#three').text(quiz[i].answers[3]);
      $('.choices').show('slow');
      $('input[name="answers"]').prop('checked', false);

    } else {
      //results
         $('#quiz').css('display', 'none');
            $('#start').css('display', 'block');
      var j = 0;
      //looping through quiz array
      $.each(quiz, function(index, val) {
      //getting correct answer
        var correctAnswer = val.correctAnswer;
        //appending question to variable
        display_result += " <div class='qtitle'>" + val.question + "</div>";
        //looping through answers array
        $.each(val.answers, function(index, val1) {
        //if answer is right
          if (users_answers[j] == correctAnswer && correctAnswer == index) {
          //append 
            display_result += "<b>You choose :</b> <div style='color:green'>" + val1 + "</div>"
          } else if (users_answers[j] == index) {
          //if answer is wrong 
            display_result += "<b>You choose :</b> <div style='color:red'>" + val1 + "</div>"
          } else if(correctAnswer== index) {
          //correct ans
            display_result += "<b>Correct Answer Was </b><div>" + val1 + "</div>"
          }else {
          //other answers
          display_result += "<div>" + val1 + "</div>"
          }

        });

        j++;//increment
      })
      //append score
      display_result +="<div id='score'>Total Score : "+ score+"</div>"
      $("#result").html(display_result);



    }
  });
});
#quiz {
  position: relative;
  height: 400px;
  width: 400px;
}

#start {
  position: absolute;
  height: 40px;
  width: 70px;
  bottom: 10%;
  right: 0%;
  background: #0080FF;
  color: #ffffff;
  padding: 6px;
  text-align: center;
  font-size: 150%;
  border-radius: 10px;
}

#start:hover {
  cursor: pointer;
  background: navy;
}

#next {
  position: absolute;
  height: 40px;
  width: 60px;
  bottom: 10%;
  right: 0%;
  background: #0080FF;
  color: #ffffff;
  text-align: center;
  padding: 4px;
  font-size: 200%;
  border-radius: 10px;
  display: none;
}

#next:hover {
  cursor: pointer;
  background: navy;
}

.choices {
  display: none;
}

#questions {
  font-size: 150%;
  height: 70px;
}

.pickone {
  display: inline;
  position: relative;
}

#results {
  display: none;
  border: 1px solid black;
  text-align: center;
  height: 400px;
  width: 450px;
}



#score {
  font-size: 150%;
  height: 70px;
}
<button id="start">Start </button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<div id="quiz">
  <div id="questions"></div>
  <div id="answers" class="choices">
    <input type="radio" name="answers" class="choices" value=0>
    <p id="zero" class="pickone"></p>
    <br/>
    <input type="radio" name="answers" class="choices" value=1>
    <p id="one" class="pickone"></p>
    <br/>
    <input type="radio" name="answers" class="choices" value=2>
    <p id="two" class="pickone"></p>
    <br/>
    <input type="radio" name="answers" class="choices" value=3>
    <p id="three" class="pickone"></p>
  </div>
  <div id="next">next</div>
</div>
<div id="result">

</div>

The correct syntax is style="color: green;"

Related