0

I'm trying to make a score quiz, pen here: https://codepen.io/stdobrescu/pen/xxbMbLK

And right now I have

var score = 0;
var scoreInt = 0;
$("#score").html(score);

$("input[type='radio']").click(function(){
scoreValue = $("input[type='radio']:checked").val();
scoreInt = parseInt(scoreValue, 10);
score += scoreInt;
console.log(scoreInt);
  console.log(score);
  $("#score").html(score);
  return scoreInt;
});

Where scoreInt is the Int value of each answer and score is the total score. Problem is my scoreInt doesn't update with each question, instead it takes the value from the first question. Should I select each question by name somehow? Does that require a for loop to go through all the questions?

Also, any ideas on how to update score in case user returns to a question and selects another value? I was thinking to subtract the scoreInt from score when it scrolls to the specific question.

Steph
  • 443
  • 2
  • 4
  • 15
  • Related: https://stackoverflow.com/questions/59887834/getting-the-value-of-the-input-field-using-jquery/59888053#59888053 This duplicate covers converting ids to classes, which isn't your issue, but it also covers contextual lookups, which **is** your issue. – Taplar Jan 24 '20 at 19:37

1 Answers1

0

The problem with the code is scoreValue = $("input[type='radio']:checked").val(); you should use scoreValue = $(this).val();

var score = 0;
var scoreInt = 0;
$("#score").html(score);

$("input[type='radio']").click(function(){
scoreValue = $(this).val();
scoreInt = parseInt(scoreValue, 10);
score += scoreInt;
console.log(scoreInt);
  console.log(score);
  $("#score").html(score);
  return scoreInt;
});
Carsten Løvbo Andersen
  • 26,637
  • 10
  • 47
  • 77