I’m trying to make simple javascript quiz with like 10 questions, and show random 5 on each page load.
I have following code for questions:
var mojaPitanja = [
{
tekst: "What is the color of the sky?",
odgovori: {
a: 'Blue',
b: 'Red',
c: 'Green'
},
indeks_korektnog_odgovora: 'a'
},
{
tekst: "In which country is located town Rome?",
odgovori: {
a: 'France',
b: 'Austria',
c: 'Italy'
},
indeks_korektnog_odgovora: 'c'
},
{
tekst: "Who was Elvis Presley?",
odgovori: {
a: 'Singer',
b: 'Writer',
c: 'Dancer'
},
indeks_korektnog_odgovora: 'a'
}
...................
];
Out of that list (with 10 questions) I want to get 5 random questions and show them on page.
This is the other part of the code I’m using to show the whole quiz on my page:
function generisiKviz(teksts, quizContainer, rezContainer, posaljiDugme){
function prikazPitanja(teksts, quizContainer){
// prostor za output i opcije odgovora
var output = [];
var odgovori;
// za svako pitanje...
for(var i=0; i<teksts.length; i++){
// prvo resetujemo listu odgovora
odgovori = [];
// za svaku opciju odgovora na dato pitanje...
for(letter in teksts[i].odgovori){
// ...dodajemo radio button
odgovori.push(
'<label>'
+ '<input type="radio" name="tekst'+i+'" value="'+letter+'">'
+ letter + ': '
+ teksts[i].odgovori[letter]
+ '</label>'
);
}
// dodajemo specificno pitanje i odgovore za dato pitanje
output.push(
'<div class="pitanje"><div class="tekst">' + teksts[i].tekst + '</div>'
+ '<div class="odgovori">' + odgovori.join('') + '</div></div>'
);
}
// finalni output koji se stavlja na stranicu
quizContainer.innerHTML = output.join('');
}
function showResults(teksts, quizContainer, rezContainer){
// prikupljanje odgovora iz celog kviza
var answerContainers = quizContainer.querySelectorAll('.odgovori');
// sacuvati odgovore korisnika..
var userAnswer = '';
var numCorrect = 0;
// za svako pitanje...
for(var i=0; i<teksts.length; i++){
// pronalazenje svakog odgovora
userAnswer = (answerContainers[i].querySelector('input[name=tekst'+i+']:checked')||{}).value;
// ako je odgovor tacan
if(userAnswer===teksts[i].indeks_korektnog_odgovora){
// dodati na sumarnu listu i sabrati koliko je tacnih...
numCorrect++;
// tacni odg zeleni
answerContainers[i].style.color = 'green';
}
// ako je odgovor netacan ili prazan
else{
// boja je, logicno, crvena...
answerContainers[i].style.color = 'red';
}
}
// prikaz ukupnog broja tacnih odgovora od sumarnog broja pitanja
rezContainer.innerHTML = numCorrect + ' pogođenih od ukupno ' + teksts.length;
}
// prikaz odgovora
prikazPitanja(teksts, quizContainer);
// kad se klikne "posalji" dugme prikaz rezultata
posaljiDugme.onclick = function(){
showResults(teksts, quizContainer, rezContainer);
}
}
var quizContainer = document.getElementById('quiz');
var rezContainer = document.getElementById('results');
var posaljiDugme = document.getElementById('submit');
And html:
<title>Page title</title>
<link rel="stylesheet" href="index.css">
<div id="quiz"></div>
<button id="submit">Pošalji odgovore</button> <button id="reloadfazon" onClick="window.location.reload()">Nova pitanja / reload</button>
<div id="results"></div>
<script src="script.js"></script>
<script>
generisiKviz(mojaPitanja, quizContainer, rezContainer, posaljiDugme);
</script>
And html:
<title>iTomik projekat :: Kviz</title>
<link rel="stylesheet" href="index.css">
<div id="quiz"></div>
<button id="submit">Pošalji odgovore</button> <button id="reloadfazon" onClick="window.location.reload()">Nova pitanja / reload</button>
<div id="results"></div>
<script src="script.js"></script>
<script>
generisiKviz(mojaPitanja, quizContainer, rezContainer, posaljiDugme);
</script>
I’m trying to use Math.floor(Math.random() but I’m lost. Any suggestions about the best approach here please? 🙂
Thanks!
>Solution :
Math.random() gives you a number between 0 and 1, so if you want a number between 0 and 9 (for the index of the question list), you multiply this by 10 (to get a number between 0 and 10) and use Math.floor() to remove decimals and the possiblility of getting a ten. The code could look something like this:
your_questions_list = [...]
let chosen_questions = []
for (let i = 0; i < 5; i++) {
let index = Math.floor(Math.random() * 10)
while (chosen_questions.includes(index)){
index = Math.floor(Math.random() * 10)
}
chosen_questions.push(i)
}
// and now to populate the list with actual questions
for (let i = 0; i < chosen_questions.length; i++) {
chosen_questions[i] = your_questions_list[chosen_questions[i]];
}
console.log(chosen_questions);
This will give you a list (chosen_questions) of 5 random questions from the list of questions
Even better, to adapt to a varying question list size you could use the .length property of a list like this:
let index = Math.floor(Math.random() * your_questions_list.length))
Update:
Here’s very short way of doing it (method is from comment above):
const shuffled = your_questions_list.sort(() => 0.5 - Math.random());
let selected = shuffled.slice(0, 5); // 5 is number of questions