I'm programming a little quiz that shows you which of the four possible products suits you best.
The different questions are asked with radio inputs and each has the appropriate value
<input class="answer__input" type="radio" id="question1" value="product1" />
<input class="answer__input" type="radio" id="question1" value="product2" />
<input class="answer__input" type="radio" id="question1" value="product3" />
<input class="answer__input" type="radio" id="question1" value="product4" />
In JavaScript i have 4 Variables:
var product1 = 0
var product2 = 0
var product3 = 0
var product4 = 0
Now i want that each time an answer is selected, the respective variable increases by 1
After 10 questions it could look like this:
var product1= 2
var product2 = 4
var product3 = 3
var product4 = 1
At the end of the Quiz i want to output the variable which is the biggest.
How can i do this in JavaScript? I would be very grateful for that help :)
You can't use the same id 4 times, and you must add name to radio input. I've rebuilt your html:
1 product<input class="answer__input question1" name="question1" type="radio" id="product1" value="product1" /><br>
2 product<input class="answer__input question1" name="question1" type="radio" id="product2" value="product2" /><br>
3 product<input class="answer__input question1" name="question1" type="radio" id="product3" value="product3" /><br>
4 product<input class="answer__input question1" name="question1" type="radio" id="product4" value="product4" /><br>
Now I've also added an event listener for the change event using a for loop on all products. In the function, I checked what option the user clicked and incremented the corresponding value.
var product1 = 0;
var product2 = 0;
var product3 = 0;
var product4 = 0;
for (i = 1; i <= 4; i++) {
document.getElementById(`product${i}`).addEventListener('change', e => {
if (e.target.value === 'product1') product1++;
else if (e.target.value === 'product2') product2++;
else if (e.target.value === 'product3') product3++;
else if (e.target.value === 'product4') product4++;
console.log(product1, product2, product3, product4);
});
}