As mentioned above, your code has some errors but I have written snippets that will achieve your aim with shorter syntax.
//Javascript code
let questionss = [{
question: "I am a ?",
options: ["Male", "Female", "Other"],
correctAnswers: 'Male',
},
{
question: "Football has letters ?",
options: [8, 5, 6],
correctAnswers: 8,
},
{
question: "VW stands for ?",
options: ["BMW", "Volkswagen", "Audi"],
correctAnswers: 'Volkswagen',
},
{
question: "What year is it ?",
options: [2017, 2015, 2019],
correctAnswers: 2019,
}
];
let questionText = document.getElementById('cd-questions');
let optiontext = document.querySelectorAll('.optiontext');
let options = document.querySelectorAll('.options');
let nextBtn = document.getElementById('next-btn');
let currentQuestion = 0;
var score = 0;
var checkedStatus = false;
setQuestion(currentQuestion); // set default question
nextBtn.addEventListener('click', e => {
e.preventDefault();
if (valForm()) setQuestion(currentQuestion); //validates and next question
});
function setQuestion(currentQuestion) {
questionText.innerText = questionss[currentQuestion].question; //set current question to the DOM
for (let i = 0; i < 3; i++) {
options[i].value = questionss[currentQuestion].options[i]; //set options value for current question
optiontext[i].innerText = questionss[currentQuestion].options[i]; //set options for current question
}
}
function valForm() {
for (let i = 0; i < 3; i++) {
if (options[i].checked) {
let userans = options[i].value;
if (questionss[currentQuestion].correctAnswers == userans) {
score++;
}
options[i].checked = false;
if (currentQuestion < questionss.length - 1) {
currentQuestion++;
if (currentQuestion == questionss.length - 1) {
nextBtn.innerText="Submit";
}
} else {
alert('Your total score is ' + score);
currentQuestion = 0;
nextBtn.innerText="Start";
}
return true;
}
}
if (checkedStatus == false) {
alert('please choose an answer');
setQuestion(currentQuestion);
}
return false;
}
<form>
<div id="cd-questions"></div>
<input class="options" name="answer" type="radio" />
<span class="optiontext"></span>
<input class="options" name="answer" type="radio" />
<span class="optiontext"></span>
<input class="options" name="answer" type="radio" />
<span class="optiontext"></span>
<div>
<button id="next-btn">Next</button>
</div>
</form>
1
solved Submit button that shows the score