1

I'm a beginner in Javascript I want to create a basic javascript quiz application, with radio buttons. At the end of the quiz, I want to have an alert message with the final score. I'm unable to display the final score. This is what I've coded yet.. HTML:

   var allQuestions = [{
    question: "Who is the Prime Minister of the United Kingdom?",
    choices: ["David Cameron", "Gordon Brown", "Winston Churchill", "Tony Blair"],
    correctAnswer: 0
  },

  {
    question: "Who is the Prime Minister of India?",
    choices: ["Rahul Gandhi", "Arvind Kejrival", "Narendra Damodardas Modi"],
    correctAnswer: 2
  },

  {
    question: "Who is the Prime Minister of America?",
    choices: ["Donald Trump", "Barack Obama", "Hilary Clinton"],
    correctAnswer: 2
  }
];

var correctAnswers = 0;
$(document).ready(function() {
  var currentquestion = 0;

  $('#question').html(allQuestions[currentquestion].question);
  $('label[for=option0]').html(allQuestions[currentquestion].choices[0] + "<br/>");
  $('label[for=option1]').html(allQuestions[currentquestion].choices[1] + "<br/>");
  $('label[for=option2]').html(allQuestions[currentquestion].choices[2] + "<br/>");

  $("#next").click(function() {
    if ($("input[name=option]:checked").val() == allQuestions[currentquestion].correctAnswer) {
      correctAnswers++;
    };
    currentquestion++;
    if (currentquestion < allQuestions.length) {
      $('#question').html(allQuestions[currentquestion].question);
      $('label[for=option0]').html(allQuestions[currentquestion].choices[0] + "<br/>");
      $('label[for=option1]').html(allQuestions[currentquestion].choices[1] + "<br/>");
      $('label[for=option2]').html(allQuestions[currentquestion].choices[2] + "<br/>");
      if (currentquestion == allQuestions.length - 1) {
        $('#next').html("Submit");
        $('#next').click(function() {
         /*If I comment out the following if statement, but retain correctAnswers++, I do get alert message,but the result is obviously wrong*/
          if ($("input[name=option]:checked").val() == allQuestions[currentquestion].correctAnswer) {
            correctAnswers++;
          }
          alert(correctAnswers);
          //alert("Your Score is " + correctAnswers + " out of " + currentquestion + " and your percentage is " + (correctAnswers*100/currentquestion) + "%");
        });

      }

    };
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<body>
  <div>
    <h3 id="question"></h3>
    <form id="form">
      <input type="radio" name="option" value="0" id="option0" checked>
      <label for='option0'>
        <br/>
      </label>
      <input type="radio" name="option" value="1" id="option1">
      <label for='option1'>
        <br/>
      </label>
      <input type="radio" name="option" value="2" id="option2">
      <label for='option2'>
        <br/>
      </label>
    </form>
  </div>
  <br/>
  <a href="#" id="next" class="button hvr-bounce-to-right">Next</a>

</body>

Please help! here is the JSFiddle.

5 Answers 5

1

Here you have a working demo.

var allQuestions = [{
    question: "Who is the Prime Minister of the United Kingdom?",
    choices: ["David Cameron", "Gordon Brown", "Winston Churchill", "Tony Blair"],
    correctAnswer: 0
  },

  {
    question: "Who is the Prime Minister of India?",
    choices: ["Rahul Gandhi", "Arvind Kejrival", "Narendra Damodardas Modi"],
    correctAnswer: 2
  },

  {
    question: "Who is the Prime Minister of America?",
    choices: ["Donald Trump", "Barack Obama", "Hilary Clinton"],
    correctAnswer: 2
  }
];


$(document).ready(function() {
  var currentquestion = 0;
  var correctAnswers = 0;
  var done = false;

  $('#question').html(allQuestions[currentquestion].question);
  $('label[for=option0]').html(allQuestions[currentquestion].choices[0] + "<br/>");
  $('label[for=option1]').html(allQuestions[currentquestion].choices[1] + "<br/>");
  $('label[for=option2]').html(allQuestions[currentquestion].choices[2] + "<br/>");

  $("#next").click(function() {
    if ($("input[name=option]:checked").val() == allQuestions[currentquestion].correctAnswer) {
      correctAnswers++;
    };

    if (done) {
      alert(correctAnswers);
    } else {
      currentquestion++;
      if (currentquestion < allQuestions.length) {
        $('#question').html(allQuestions[currentquestion].question);
        $('label[for=option0]').html(allQuestions[currentquestion].choices[0] + "<br/>");
        $('label[for=option1]').html(allQuestions[currentquestion].choices[1] + "<br/>");
        $('label[for=option2]').html(allQuestions[currentquestion].choices[2] + "<br/>");
        if (currentquestion == allQuestions.length - 1) {
          $('#next').html("Submit");
          done = true;
        }
      }
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<body>
  <div>
    <h3 id="question"></h3>
    <form id="form">
      <input type="radio" name="option" value="0" id="option0" checked>
      <label for='option0'>
        <br/>
      </label>
      <input type="radio" name="option" value="1" id="option1">
      <label for='option1'>
        <br/>
      </label>
      <input type="radio" name="option" value="2" id="option2">
      <label for='option2'>
        <br/>
      </label>
    </form>
  </div>
  <br/>
  <a href="#" id="next" class="button hvr-bounce-to-right">Next</a>

</body>

Sign up to request clarification or add additional context in comments.

4 Comments

Great! Be aware that the answer with the green check isn't the best one. A click event inside a click event is not really a good way.
any specific reason for that?, I found @PierreC. most explicit and self-explanatory ,so I ticked it.
btw,this is my first program,and I need some feedback.Can you help?
It's hard to explain for me why, but it's not clean code. Suppose you are making another click event inside, and again, and again. It's difficult to read how it works and which click event is active. So it's better to never start with duplicate code, not at all in your own funcion. Beside that it is not necessary.
1

Here is my solution to your problem. You were incrementing currentQuestion one extra time after the last question.

https://jsfiddle.net/k7874vjn/5/

if(currentquestion<allQuestions.length){
                $('#question').html(allQuestions[currentquestion].question);
                $('label[for=option0]').html(allQuestions[currentquestion].choices[0]+"<br/>");
                $('label[for=option1]').html(allQuestions[currentquestion].choices[1]+"<br/>");
                $('label[for=option2]').html(allQuestions[currentquestion].choices[2]+"<br/>");
                if(currentquestion==allQuestions.length-1){
                    $('#next').html("Submit");
                    $('#next').click(function(){
                        if($("input[name=option]:checked").val()==allQuestions[currentquestion].correctAnswer){
                            correctAnswers++;
                        }
                        alert(correctAnswers);
                        //alert("Your Score is " + correctAnswers + " out of " + currentquestion + " and your percentage is " + (correctAnswers*100/currentquestion) + "%");
                    });

                } else
            currentquestion++; //MOVED HERE

            };

3 Comments

Getting 4 good answers for 3 questions. I don't think the code was bad. Just setting the click listener twice see my answer
@henrikmerlander that doesn't work..the first next takes two clicks to move to the next question and morevoer, the final result displays 2 even when all three answers were correct
I'm so sorry,I wasn't entering the right answer for the last question.My bad.Sorry.And thanks man.But, still the first next requires two clicks to move to the next question.
1

i fix your code

jsFiddle

the problem is here

if($("input[name=option]:checked").val()==allQuestions[currentquestion].correctAnswer){
    correctAnswers++;
}

8 Comments

It still doesn't work..The final results are flawed.Even with three correct answers,I'm getting 2 in the alert box
@PierreC.,oh sorry I didn't notice that.But, does that make any difference to my problem
@PierreC. oh sorry it didn't care about it, but now i update my fiddle and it's work fine for me
@Rashid i update my answer fiddle and it's work fine
@shayanypn not yet..even if when all three are correct..the alert message shows 2
|
1

The problem is that you set another click event callback on your next button while the first is still active.

Just add $('#next').unbind("click"); like this:

$('#next').html("Submit");
$('#next').unbind("click");
$('#next').click(...

This remove the click listener on your button before you set a new one.

Code snippet:

var allQuestions = [{
    question: "Who is the Prime Minister of the United Kingdom?",
    choices: ["David Cameron", "Gordon Brown", "Winston Churchill", "Tony Blair"],
    correctAnswer: 0
  },

  {
    question: "Who is the Prime Minister of India?",
    choices: ["Rahul Gandhi", "Arvind Kejrival", "Narendra Damodardas Modi"],
    correctAnswer: 2
  },

  {
    question: "Who is the Prime Minister of America?",
    choices: ["Donald Trump", "Barack Obama", "Hilary Clinton"],
    correctAnswer: 2
  }
];

var correctAnswers = 0;
$(document).ready(function() {
  var currentquestion = 0;

  $('#question').html(allQuestions[currentquestion].question);
  $('label[for=option0]').html(allQuestions[currentquestion].choices[0] + "<br/>");
  $('label[for=option1]').html(allQuestions[currentquestion].choices[1] + "<br/>");
  $('label[for=option2]').html(allQuestions[currentquestion].choices[2] + "<br/>");

  $("#next").click(function() {
    if ($("input[name=option]:checked").val() == allQuestions[currentquestion].correctAnswer) {
      correctAnswers++;
    };
    currentquestion++;
    if (currentquestion < allQuestions.length) {
      $('#question').html(allQuestions[currentquestion].question);
      $('label[for=option0]').html(allQuestions[currentquestion].choices[0] + "<br/>");
      $('label[for=option1]').html(allQuestions[currentquestion].choices[1] + "<br/>");
      $('label[for=option2]').html(allQuestions[currentquestion].choices[2] + "<br/>");
      if (currentquestion == allQuestions.length - 1) {
        $('#next').html("Submit");
        $('#next').unbind("click");
        $('#next').click(function() {
         /*If I comment out the following if statement, but retain correctAnswers++, I do get alert message,but the result is obviously wrong*/
          if ($("input[name=option]:checked").val() == allQuestions[currentquestion].correctAnswer) {
            correctAnswers++;
          }
          alert(correctAnswers);
          //alert("Your Score is " + correctAnswers + " out of " + currentquestion + " and your percentage is " + (correctAnswers*100/currentquestion) + "%");
        });

      }

    };
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<body>
  <div>
    <h3 id="question"></h3>
    <form id="form">
      <input type="radio" name="option" value="0" id="option0" checked>
      <label for='option0'>
        <br/>
      </label>
      <input type="radio" name="option" value="1" id="option1">
      <label for='option1'>
        <br/>
      </label>
      <input type="radio" name="option" value="2" id="option2">
      <label for='option2'>
        <br/>
      </label>
    </form>
  </div>
  <br/>
  <a href="#" id="next" class="button hvr-bounce-to-right">Next</a>

</body>

4 Comments

tried doing that..it still shows 2 when all three answers are correct
Well I have 3 when I run my code snippet... you check the first answer in question 1 and then the last answer for the others ?
I'm so sorry,I wasn't entering the right answer for the last question.My bad.Sorry.And thanks man.
btw,this is my first program,and I need some feedback.Can you help?
0

If you comment the if and correctAnswers++ sentence, your code works rightly.

         /*If I comment out the following if statement, but retain correctAnswers++, I do get alert message,but the result is obviously wrong*/
          /*if ($("input[name=option]:checked").val() == allQuestions[currentquestion].correctAnswer) {
            correctAnswers++;
          }*/
          alert(correctAnswers);
          alert("Your Score is " + correctAnswers + " out of " + currentquestion + " and your percentage is " + (correctAnswers*100/currentquestion) + "%");

3 Comments

that's awesome man..can you please elaborate/explain your answer?
Of course, when the user clicks submit button, the correctAnswers variable already has the right value. At that moment, the currentquestion is equal to 3. So, in the comparison allQuestions[currentquestion].correctAnswer is not defined and your original code finishes its execution without successful.
If you display an alert with correctAnswers before or instead of comparision, you will see that its value is 3. alert(correctAnswers)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.