I'm creating this simple quiz with 6 questions that I'm storing in an array. What I'm stuck with is that when you've reached the last question and you click 'Next', I'd like to show your results along with a text and a 'Restart' button.
What happens now though is that it show the last question again but without any answer-butons (I'm not getting into that if statement).
I'm pretty new to js, here's my code.
const startQuiz = document.querySelector('.container__start-btn');
const theQuestion = document.querySelector('.container__question');
const fourAnswers = document.querySelector('.container__answers');
const counter = document.querySelector('.container__counter__correct-answer');
const questionCounter = document.querySelector('.container__counter__question-nr');
const containerCounter = document.querySelector('.container__counter');
let currentQuestion = 0;
let count = 0;
const showQuestion = () => {
startQuiz.innerText = 'NEXT';
while (fourAnswers.firstChild) {
fourAnswers.removeChild(fourAnswers.firstChild);
}
theQuestion.innerText = questions[currentQuestion].question;
checkCounters();
}
const checkCounters = () => {
counter.textContent = `Score: ${count}`;
questionCounter.textContent = `Question: ${currentQuestion + 1}/${questions.length}`;
generateAnswers();
}
const generateAnswers = () => {
questions[currentQuestion].answers.forEach(answer => {
const button = document.createElement('button');
button.innerText = answer.answer;
if (answer.correct) {
button.classList.add('right');
}
button.classList.add('btn');
fourAnswers.appendChild(button);
fourAnswers.classList.remove('hide');
})
fourAnswers.onclick = () => {
const selected = event.target;
if (selected.classList.contains('right')) {
selected.classList.add('selectedRight');
count++;
counter.textContent = `Score: ${count}`;
}
if (!selected.classList.contains('right')) {
selected.classList.add('selectedWrong');
}
const rightA = document.querySelector('.right');
rightA.classList.add('selectedRight');
}
currentQuestion++;
if (currentQuestion > questions.length) {
console.log('inside if');
startQuiz.innerText = 'START';
theQuestion.innerText = `Good job! You got ${count} correct answers out of ${questions.length}. Press 'START' to go again.`;
count = 0;
currentQuestion = 0;
}
}
const questions = [
{
question: 'What is the capital of Greece?',
answers: [
{ answer: 'Athens', correct: true },
{ answer: 'Gothenburg', correct: false },
{ answer: 'Madrid', correct: false },
{ answer: 'Berlin', correct: false }
]
},
{
question: 'What is the capital of Sweden?',
answers: [
{ answer: 'Stockholm', correct: true },
{ answer: 'Lisboa', correct: false },
{ answer: 'Paris', correct: false },
{ answer: 'New York', correct: false }
]
},
{
question: 'What is the capital of Portugal?',
answers: [
{ answer: 'Lisboa', correct: true },
{ answer: 'Valencia', correct: false },
{ answer: 'Porto', correct: false },
{ answer: 'London', correct: false }
]
},
{
question: 'What is the capital of Argentina?',
answers: [
{ answer: 'Buenos Aires', correct: true },
{ answer: 'Santiago', correct: false },
{ answer: 'Amsterdam', correct: false },
{ answer: 'Beijing', correct: false }
]
},
{
question: 'What is the capital of Thailand?',
answers: [
{ answer: 'Bangkok', correct: true },
{ answer: 'Manila', correct: false },
{ answer: 'Rome', correct: false },
{ answer: 'Nicosia', correct: false }
]
},
{
question: 'What is the capital of Denmark?',
answers: [
{ answer: 'Copenhagen', correct: true },
{ answer: 'Oslo', correct: false },
{ answer: 'Beirut', correct: false },
{ answer: 'Los Angeles', correct: false }
]
}
]
startQuiz.addEventListener('click', showQuestion);
You should change the line 51 as follows.
if (currentQuestion >= questions.length) {
This is because the questions.length is 6 and the counter currentQuestion is 6 at the last question.
-- edit --
OK, try to modify like the following.
const showQuestion = () => {
if (currentQuestion >= questions.length) {
console.log('inside if');
startQuiz.innerText = 'START';
theQuestion.innerText = `Good job! You got ${count} correct answers out of ${questions.length}. Press 'START' to go again.`;
count = 0;
currentQuestion = 0;
return;
}
startQuiz.innerText = 'NEXT';
while (fourAnswers.firstChild) {
fourAnswers.removeChild(fourAnswers.firstChild);
}
theQuestion.innerText = questions[currentQuestion].question;
checkCounters();
currentQuestion++;
}
And delete currentQuestion++; from generateAnswers()
Difficult to be sure without a full reproducible jsfiddle, but I think it should be:
if (currentQuestion >= questions.length)
instead of:
if (currentQuestion > questions.length)
Put your if in the beginning of the function and return inside of it so that you exit the function and do nothing else once you go into the if.
Currently what's happening is that the foreach is triggered even when the currentQuestion has passed the questions.length.
Also add the check to be more or equal.
const generateAnswers = () => {
if (currentQuestion >= questions.length) {
console.log('inside if');
startQuiz.innerText = 'START';
theQuestion.innerText = `Good job! You got ${count} correct answers out of ${questions.length}. Press 'START' to go again.`;
count = 0;
currentQuestion = 0;
return; // end the function here so the other logic doesn't trigger.
}
questions[currentQuestion].answers.forEach(answer => {
const button = document.createElement('button');
button.innerText = answer.answer;
if (answer.correct) {
button.classList.add('right');
}
button.classList.add('btn');
fourAnswers.appendChild(button);
fourAnswers.classList.remove('hide');
})
fourAnswers.onclick = () => {
const selected = event.target;
if (selected.classList.contains('right')) {
selected.classList.add('selectedRight');
count++;
counter.textContent = `Score: ${count}`;
}
if (!selected.classList.contains('right')) {
selected.classList.add('selectedWrong');
}
const rightA = document.querySelector('.right');
rightA.classList.add('selectedRight');
}
currentQuestion++;
}
Related
I'm stuck with this error when I try to press Next to switch question & answer.
I'm currently using Vue2.
What should I change if i want to use nextbtn function to switch question & answer at the same time.
Error:"[Vue warn]: Error in v-on handler: 'ReferenceError: nextBtn is not defined'
found in
--->
"
HTML
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<div id="app1">
<display-question></display-question>
</div>
JS
Vue.component('display-question',{
data: function(){
return{
counter: 0,
currentQuestion: 0,
answered: 0,
showWrongQuestion: false,
wrongQuestions: [],
temp: [],
wrongAnswers: 0,
correctAnswers: 0,
message: "Enter your answer here",
WhatAnswer: "default",
questions: [
{
question: 'What is the capital of Ukrain ?',
answer: [
'Kyiv',
' Kabul',
' Buenos Aires',
' Praia'
],
correct_answer: 0,
selected: null,
sense: 0
},
{
question: 'When was Queen Elizabeth II death ?',
answer: [
'11/09/2022',
'08/09/2022',
'12/08/2022',
'07/09/2022'
],
correct_answer: 1,
selected: null,
sense: 0
},
{
question: 'How many bones are there in human body?',
answer: [
'206',
'186',
'209',
'190'
],
correct_answer: 0,
selected: null,
sense: 0
},
{
question: 'Who were the 30th president of ?',
answer: [
'Julia Eileen Gillard',
'John Winston Howard ',
' Scott John Morrison ',
'Anthony Albanese,'
],
correct_answer: 2,
selected: null,
sense: 0
},
{
question: 'What is the biggest continent?',
answer: [
'Oceania',
'Europe',
'Asia',
'Africa'
],
correct_answer: 2,
selected: null,
sense: 0
}
],
}},
methods: {
backBtn:function () {
if (this.question > 0) {
this.question = this.question - 1;
}
},
nextBtn: function(){
this.answered < this.questions.length ? this.answered++ : '';
if(!nextBtn.hasAttribute('disabled') && this.currentQuestion < (questionsLength -1)) {
this.currentQuestion++; //I think error happen here
answers.forEach(answer => {
answer.classList.contains('selected') ? answer.classList.remove('selected') : '';
});
nextBtn.setAttribute('disabled', '');
}
else if(this.currentQuestion >= (questionsLength -1)) {
this.questions.forEach( (question) => {
if(question.selected == question.correct_answer && question.sense ==0) {
this.correctAnswers++;
question.sense = 1;
} else if(question.selected != question.correct_answer && question.sense ==0) {
this.wrongAnswers++;
question.sense = 1;
let temp = {};
temp.answers = question.answers;
temp.question = question.question;
temp.correct_answer = question.correct_answer;
temp.selected = question.selected;
this.wrongQuestions.push(temp);
}
});
result.classList.add('active');
question.classList.add('blur');
}
},
calculateResult: (questions) => {
var correct;
for(var i=0; i< questions.length; i++) {
this.questions[i].selected == questions[i].correct ? correct++ : '';
}
return (correct / questions.length) * 100;
},
selectAnswer: function(a) {
var choice = a.currentTarget,
answers = document.querySelectorAll('.answers span'),
nextBtn = document.querySelector('.next-btn');
answers.forEach(answer => {
answer.classList.contains('selected') ? answer.classList.remove('selected') : '';
});
choice.classList.add('selected');
this.questions[this.currentQuestion].selected = choice.dataset.index;
nextBtn.removeAttribute('disabled');
},
},
mounted() {
var nextBtn = this.$el.querySelector('.next-btn'),
wrongAnswersBtn = this.$el.querySelector('.show-wrong-ones'),
backBtn = this.$el.querySelector('.back-Btn'),
answers = this.$el.querySelectorAll('.answers span'),
questionsLength = this.questions.length,
result = this.$el.querySelector('.result'),
question = this.$el.querySelector('.question'),
closeResult = this.$el.querySelector('.result button.close'),
wrongQuestions = this.$el.querySelector('.wrong-questions'),
showMyResults = this.$el.querySelector('#return-to-result');
},
template: '<div><div v-if="counter < questions.length"> <h2>{{questions[currentQuestion].question }}</h2></br> <span class=answer v-for="(answer, index) in questions[currentQuestion].answer" :key="index" v-bind:data-index="index" #click="selectAnswer">{{ answer }}</span><p><button class="backBtn" v-on:click="backBtn">BACK</button> <button class="next-btn" v-on:click="nextBtn" disabled > {{ currentQuestion < (questions.length -1) ? "Next" : "Result!" }} </button></p> </div> <div class="result"><div class="success"></div></div></div>',
})
var test1 = new Vue({
el: "#app1",
data: {
},
});
It seems like what's undefined is not the nextBtn method, but the nextBtn variable that you referenced inside the nextBtn method (from this line if(!nextBtn.hasAttribute('disabled') && this.currentQuestion < (questionsLength -1)) {), on mounted you initialized some variables, you should declare those variables first on data(), then initialize in the mounted. When you're accessing the data, you should use this like this.nextBtn, also try to change the name of the variables so that they're not the same as the name of the method (e.g. in here you have nextBtn as a function and nextBtn as a variable).
How can I fix this problem. Actually this is an exercise about how to use debugger but I couldn't solve the problem.
Fix the cutestCat function. Should return the cat with the highest cuteness
rating.
*/
function cutestCat(cats) {
let cutest;
let i = 0;
debugger
while (i < cats.length) {
const cat = cats[i];
if (cat > cutest) {
cutest = cat.cuteness;
}
i++;
}
return cutest;
}
const cats = [
{ name: 'Fluffy', cuteness: 9 },
{ name: 'Princess', cuteness: 6 },
{ name: 'Tiger', cuteness: 7 },
{ name: 'Indie', cuteness: 5 },
]
console.log(cutestCat(cats)); // { name: 'Fluffy', cuteness: 9 }
You have two issues:
you need to compare cat cuteness not cats ie:
if (cat.cuteness > cutest.cuteness){
}
this comparison requires that the cutest variable holds a cat with a cuteness property, but starts as undefined which will give you an error.
One possible fix is starting with it as the first cat in the array and initilizing i as 0.
This is the whole snippet:
function cutestCat(cats) {
let cutest = cats[0];
let i = 1;
while (i < cats.length) {
const cat = cats[i];
if (cat.cuteness > cutest.cuteness) {
cutest = cat;
}
i++;
}
return cutest;
}
const cats = [
{ name: 'Fluffy', cuteness: 9 },
{ name: 'Princess', cuteness: 6 },
{ name: 'Tiger', cuteness: 7 },
{ name: 'Indie', cuteness: 5 },
]
console.log(cutestCat(cats));
Fix with either...
function cutestCat(cats) {
let cutest=-MAX_SAFE_INTEGER, cutestCat;
let i = 0;
debugger
while (i < cats.length) {
const cat = cats[i];
if (cat.cuteness > cutest) { // note the new comparison
cutest = cat.cuteness;
cutestCat = cat; // note the recording of the object
}
i++;
}
return cutestCat; // note returning the object
}
Or, prettier...
function cutestCat(cats) {
let sorted = cats.slice().sort((a, b) => b.cuteness-a.cuteness);
return sorted.length ? sorted[0] : null;
}
The problem lies in the if of the while loop. You are comparing cat(object) variable with cutest(numeric) variable.
So rather that storing cuteness in cutest variable, store the object itself. And then you can compare cuteness of both those objects in the if condition.
That is:
function cutestCat(cats) {
let cutest = cats[0];
let i = 1;
debugger
while (i < cats.length) {
const cat = cats[i];
if (cat.cuteness > cutest.cuteness) {
cutest = cat;
}
i++;
}
return cutest;
}
const cats = [
{ name: 'Fluffy', cuteness: 9 },
{ name: 'Princess', cuteness: 6 },
{ name: 'Tiger', cuteness: 7 },
{ name: 'Indie', cuteness: 5 },
];
console.log(cutestCat(cats)); // { name: 'Fluffy', cuteness: 9 }
You might also want to write some conditions to check if the array passed (i.e. cats) is empty or not.
There are 2 simple ways to solve this problem.
Reduce
function cutestCat(array) {
return array.reduce((acc, rec) => {
console.log("acc", acc);
return acc.cuteness < rec.cuteness ? rec : acc;
});
}
For loop
function cutestCat(array) {
if (!array.length) {
return "some default value";
}
let result = array[0];
for (let i = 1; i < array.length; i += 1) {
const current = array[i];
if (current.cuteness > result.cuteness) {
result = current;
}
}
return result;
}
In your example, you need to make a comparison by the cuteness field, and not compare objects. All objects have different references, so your condition won't work.
You can use array.forEach to loop through them and check for the highest cuteness, like so:
function cutestCat(cats) {
let cutest = cats[0]; // to avoid null reference
cats.forEach(cat => {
if (cat.cuteness > cutest.cuteness) {
cutest = cat;
}
});
return cutest;
}
function cutestCat(cats) {
let cutest;
let i = 0;
while (i < cats.length) {
const cat = cats[i];
// if there is no cutest cat to start with, it means this is the
// first cat, set it as the cutest cat and skip the cuteness
// comparison
if(!cutest) {
cutest = cat;
continue;
}
// if there is already a cat that is considered cutest,
// compare it with current cat and update cutest if
// the current cat is more cuter than the one that is already
// considered cutest
if (cat.cuteness > cutest.cuteness) {
cutest = cat;
}
i++;
}
return cutest;
}
const cats = [
{ name: 'Fluffy', cuteness: 9 },
{ name: 'Princess', cuteness: 6 },
{ name: 'Tiger', cuteness: 7 },
{ name: 'Indie', cuteness: 5 },
]
console.log(cutestCat(cats)); // { name: 'Fluffy', cuteness: 9 }
let myQuestions = [
{
question: "What's 2+2?",
answers: [
{ text: "4", correct: true },
{ text: "2", correct: false },
{ text: "10", correct: false },
{ text: "1", correct: false },
],
},
{
question: "What's 10+10?",
answers: [
{ text: "20", correct: true },
{ text: "2", correct: false },
{ text: "18", correct: false },
{ text: "0", correct: false },
],
},
];
function startQuiz() {
//container.style.visibility = "visible";
//btn_start.style.visibility = "hidden";
showQuestion(myQuestions[0]);
}
function showQuestion(questionAndAnswers) {
alert(questionAndAnswers.question);
//const shuffledAnswers = _.shuffle(questionAndAnswers.answers);
//questionTag.innerText = questionAndAnswers.question;
//answerTag[0].innerText = shuffledAnswers[0].text;
//answerTag[1].innerText = shuffledAnswers[1].text;
//answerTag[2].innerText = shuffledAnswers[2].text;
//answerTag[3].innerText = shuffledAnswers[3].text;
}
function nextQuestion() {
showQuestion(myQuestions[0]);
}
<input type='button' value='Start Quiz' onclick=startQuiz() />
<input type='button' value='Next question' onclick=nextQuestion() />
First question gets called when I press start quiz and it access my first object in my array, how do I make the function next question work which basically access the next object by incrementing so lets say I add question 3 it keeps on going.
Take a global variable let currentQuestionIndex = 0; & update your nextQuestion function as below. Also update your startQuiz() function and set currentQuestionIndex = 0; & replace showQuestion(myQuestions[0]); with nextQuestion();
function nextQuestion() {
// Add condition so at last question it will stop at last question
if (myQuestions.length > currentQuestionIndex) {
showQuestion(myQuestions[currentQuestionIndex]);
currentQuestionIndex++;
}
}
function startQuiz() {
container.style.visibility = "visible";
btn_start.style.visibility = "hidden";
currentQuestionIndex = 0;
nextQuestion();
}
Your complete code will look like below. I have commented some of your code just for testing purpose.
let currentQuestionIndex = 0;
let myQuestions = [
{
question: "What's 2+2?",
answers: [
{ text: "4", correct: true },
{ text: "2", correct: false },
{ text: "10", correct: false },
{ text: "1", correct: false },
],
},
{
question: "What's 10+10?",
answers: [
{ text: "20", correct: true },
{ text: "2", correct: false },
{ text: "18", correct: false },
{ text: "0", correct: false },
],
},
];
function startQuiz() {
//container.style.visibility = "visible";
//btn_start.style.visibility = "hidden";
currentQuestionIndex = 0;
nextQuestion();
}
function showQuestion(questionAndAnswers) {
// temp code for alert
alert(questionAndAnswers.question);
//const shuffledAnswers = _.shuffle(questionAndAnswers.answers);
//questionTag.innerText = questionAndAnswers.question;
//answerTag[0].innerText = shuffledAnswers[0].text;
//answerTag[1].innerText = shuffledAnswers[1].text;
//answerTag[2].innerText = shuffledAnswers[2].text;
//answerTag[3].innerText = shuffledAnswers[3].text;
}
function nextQuestion() {
// Add condition so at last question it will stop at last question
if (myQuestions.length > currentQuestionIndex) {
showQuestion(myQuestions[currentQuestionIndex]);
currentQuestionIndex++;
}
}
<input type='button' value='Start Quiz' onclick=startQuiz() />
<input type='button' value='Next question' onclick=nextQuestion() />
You can store your current question index and use that to step through the list:
let currentQuestionIndex = 0;
let myQuestions = [
{
question: "What's 2+2?",
answers: [
{ text: "4", correct: true },
{ text: "2", correct: false },
{ text: "10", correct: false },
{ text: "1", correct: false },
],
},
{
question: "What's 10+10?",
answers: [
{ text: "20", correct: true },
{ text: "2", correct: false },
{ text: "18", correct: false },
{ text: "0", correct: false },
],
},
];
function startQuiz() {
container.style.visibility = "visible";
btn_start.style.visibility = "hidden";
showQuestion(myQuestions[0]);
}
function showQuestion(questionAndAnswers) {
const shuffledAnswers = _.shuffle(questionAndAnswers.answers);
questionTag.innerText = questionAndAnswers.question;
answerTag[0].innerText = shuffledAnswers[0].text;
answerTag[1].innerText = shuffledAnswers[1].text;
answerTag[2].innerText = shuffledAnswers[2].text;
answerTag[3].innerText = shuffledAnswers[3].text;
}
function nextQuestion() {
const nextIndex = currentQuestionIndex + 1;
if (nextIndex < myQuestions.length - 1) {
showQuestion(myQuestions[nextIndex]);
currentQuestionIndex = nextIndex;
} else {
console.log('end of question list');
}
}
I have these 2 arrays of information. I want to resolve this problem: (Given the name of an user and a required permission, return true if
the user have that permission and false otherwise.)
const groups = [
{
id: 1,
name: 'admins',
permissions: ['CREATE', 'DELETE', 'READ', 'WRITE'],
},
{
id: 2,
name: 'readers',
permissions: ['READ'],
},
{
id: 3,
name: 'writers',
permissions: ['WRITE'],
},
{
id: 4,
name: 'managers',
permissions: ['CREATE', 'DELETE'],
}
];
const users = [
{
name: 'john',
groups: [1],
},
{
name: 'mary',
groups: [2, 3],
},
{
name: 'alice',
groups: [2]
},
{
name: 'bob',
groups: [3],
},
{
name: 'eve',
groups: [2, 4],
},
];
the code I've written so far:
function userHasPermission(userName, requiredPermission) {
//looping through first array
for (i = 0; i < users.length; i++) {
if (users[i].name === userName) {
// looping through the second array
for (j = 0; j < groups.length; j++) {
//here I don't know how to resolve this comparison, because as far as I understand it, the script has to check if userName is a valid ID inside groups array?
if (users[i].groups.includes(groups[j].id) && (groups[j].permissions.includes(requiredPermission))) {
return true;
} else {
return false;
}
}
}
}
};
userHasPermission("mary", "WRITE");
I'm new to Vanilla JavaScript and I'm stuck at this point, any help will be appreciated!
function userHasPermission(userName, requiredPermission) {
//looping through first array
for (i = 0; i < users.length; i++) {
if (users[i].name === userName) {
// looping through the second array
for (j = 0; j < groups.length; j++) {
if (users[i].groups.includes(groups[j].id) && (groups[j].permissions.includes(requiredPermission))) {
return true;
} else {
continue; // don’t return false yet.
}
}
}
}
// only when you’ve checked all possibilities
// still find no match, now you can return definitely
return false;
};
Above is imperative for-loop style based on your code. I personally prefer more functional code style. For your reference:
function userHasPermission(userName, requiredPermission) {
const targetUser = users.find(user => user.name === userName);
if (!targetUser) return false;
const userGroups = groups.filter(g => targetUser.groups.includes(g.id));
const permissions = userGroups.flatMap(g => g.permissions);
return permissions.includes(requiredPermission);
}
function userHasPermission(userName, requiredPermission) {
const user = users.find(u => u.name === userName);
let result = false;
user.groups.forEach(id => {
const group = groups.find(g => g.id === id);
result = group.permissions.includes(requiredPermission);
});
return result;
};
userHasPermission("mary", "WRITE");
I'm creating this code to create a quiz.
The undefined error shows up when I'm trying to setData to give my buttons key strings. I'm doing so to try use that to check whether the answer buttons get assigned certain classes "correct" or "incorrect".
These buttons aren't fully fleshed out yet. Because I'm stuck on this one part.
But, I get an undefined error in the selectAnswer function loop. I'm stuck and don't know what I'm doing wrong. Any pointers would be nice.
// This document, when the start button is clicked, shows questions, & starts the timer
var startButton = document.getElementById("start-btn");
var questionContainerEl = document.getElementById("question-container");
var startScreen = document.getElementById("start-screen");
var questionTitle = document.getElementById("question");
var choiceButtons = document.getElementById("choice-buttons");
//var buttonVal = 0;
var score = 0;
var shuffleQuestions, currentQindex;
var i = 0;
//Object Container to hold questions and answers
const questions = [{
question: "What is 2 + 2?",
answers: [
{text: "4", correct: "true"},
{text: "2", correct: "false"},
{text: "3", correct: "false"},
{text: "5", correct: "false"}
]
},
{
question: "What is 4*4?",
answers: [{text: '8', correct: "false"},
{text: '16',correct: "false"},
{text: '2', correct: "false"},
{text: '6', correct: "false"},
]
},
{
question: "Solve for x. y = 3x - 6",
answers: [{text: '6', correct: "false"},
{text: '3', correct: "false"},
{text: '2', correct: "false"},
{text: "idk", correct: "false"}]
}];
startButton.addEventListener('click',startGame);
//Start game function shows Question Cont. Shuffles Questions on an Arr.
function startGame() {
startScreen.classList.add('hide');
shuffleQuestions = questions.sort(() => Math.random() - .5);
currentQindex = 0;
questionContainerEl.classList.remove('hide');
setNextQuestion();
}
//Erases question and finds next one on Arr.
function setNextQuestion() {
resetState();
showQuestion(shuffleQuestions[currentQindex])
}
//Shows question as well as answers.
function showQuestion(questions) {
questionTitle.innerText = questions.question;
console.log(questionTitle);
var ansLength = Object.keys(questions.answers).length;
var ans;
for(i = 0; i < ansLength; i++) {
//When the answer button is selected questions goes to next object element
ans = questions.answers[i];
console.log(ans);
var button = document.createElement("button");
button.innerText = ans.text;
button.classList.add('btn');
if(ans.correct === "true") {
button.correct = ans.correct;
console.log("button:" + button.correct);
}
button.addEventListener("click", selectAnswer);
choiceButtons.appendChild(button);
}
}
//removes buttons from choices.
function resetState() {
while(choiceButtons.firstChild) {
choiceButtons.removeChild(choiceButtons.firstChild)
}
}
function selectAnswer(e) {
var selectedButton = e.target;
var isCorrect = selectedButton.dataset.correct;
setStatusClass(document.body, isCorrect);
var ar = Array.from(choiceButtons.children)
for (buttons in ar) {
setStatusClass(buttons, buttons.dataset.isCorrect);
}
}
function setStatusClass(element, correct) {
clearStatusClass(element);
if (correct) {
element.classList.add("correct");
} else {
element.classList.add("incorrect");
}
}
function clearStatusClass(element){
element.classList.remove("correct");
element.classList.remove("incorrect");
}'''