user9593500
user9593500

Reputation: 1

Count correct answers from radio input with Javascript

I have to count the correct answers from 10 different questions. The questions are formulated like so:

<input type='radio' name='question1'>answer wrong<br>
<input type='radio' name='question1' value='correct'>answer correct<br>
<input type='radio' name='question2'>answer wrong<br>
<input type='radio' name='question2' value='correct'>answer correct<br>

This script runs every time a question is answered:

    var input = document.getElementsByTagName("input")
for (var i=0;i<input.length;i++) {
if (input[i].value=="correct") {
    if (input[i].checked==true){
        correct++
    }
}
console.log(correct)
}

For some reason, after one question is answered correctly, the counter will keep adding 1 var correct for every answer given after that, even if the answer is wrong or not checked at all. If there are 2 questions answered correctly, it will keep adding 2 for every answered question after that, and so on.

Upvotes: 0

Views: 1401

Answers (2)

Get Off My Lawn
Get Off My Lawn

Reputation: 36351

A quick way to do this is to use querySelectorAll to get all the correctly checked answers:

document.querySelectorAll('input[type=radio][value=correct]:checked').length
  • input we only want to look at inputs
  • [type=radio] the input must be a radio button
  • [value=correct] the radio must have a value of correct
  • :checked the correct radio must be checked

Here is a working example:

Array.from(document.querySelectorAll('input[type=radio]')).forEach(item => {
  item.addEventListener('click', e => {
    let correct = document.querySelectorAll('input[type=radio][value=correct]:checked').length
    console.log(correct)
  })
})
<input type='radio' name='question1'>answer wrong<br>
<input type='radio' name='question1' value='correct'>answer correct<br>
<input type='radio' name='question2'>answer wrong<br>
<input type='radio' name='question2' value='correct'>answer correct<br>

Upvotes: 2

mewc
mewc

Reputation: 1447

it is counting the correct answers at any one time, you are just adding all the correct answers to a variable that is never reset.

There are many ways to do this. You can reset the counter variable each time it checks all the answers, and at the end check how many are correct.

var input = document.getElementsByTagName("input")
for (var i=0;i<input.length;i++) {
if (input[i].value=="correct") {
    if (input[i].checked==true){
        correct++
    }
}
console.log(correct);
if(i==input.length)correct = 0;
}

if(correct == 10){console.log("player got 100%");}

Upvotes: 0

Related Questions