const allQuestions =
[ { question : 'What is the capital of France?'
, choices : [ 'Berlin', 'Paris', 'London' ]
, correctAnswer: 1
}
, { question : 'What is the tallest mountain in the world?'
, choices : [ 'Mount Everest', 'K2', 'Mauna Kea' ]
, correctAnswer: 0
}
, { question : 'Which planet is known as the Red Planet?'
, choices : [ 'Venus', 'Mars', 'Jupiter' ]
, correctAnswer: 1
}
]
function* qList(arr) { for (let q of arr) yield q }
const libQuestion = document.querySelector('h1')
, formReplies = document.getElementById('list')
, btNext = document.querySelector('button')
, DomParser = new DOMParser()
, qListRead = qList( allQuestions )
, score = { correct: 0, count:0 }
;
var currentAnswer = ''
;
function setNewQuestion()
{
formReplies.innerHTML = ''
let newQuestion = qListRead.next()
if (!newQuestion.done)
{
libQuestion.textContent = newQuestion.value.question
currentAnswer = newQuestion.value.correctAnswer
++score.count
newQuestion.value.choices.forEach((choice,indx)=>
{
let line = `<label><input type="radio" name="answer" value="${indx}">${ choice}</label>`
, inLn = (DomParser.parseFromString( line, 'text/html')).body.firstChild
;
formReplies.appendChild(inLn)
})
}
else
{
libQuestion.textContent = ` Score = ${score.correct} / ${score.count}`
btNext.disabled = true
}
}
setNewQuestion()
btNext.onclick=()=>
{
if (formReplies.answer.value)
{
score.correct += ( currentAnswer == formReplies.answer.value )
setNewQuestion()
}
}
<h1></h1>
<p></p>
<form id="list"></form>
<br>
<button>next</button>