I am doing a quiz that consists of 3 questions and each question has 3 options. Only one question is displayed on the screen at a time. For answer a the value is 2 points, for answer b the value is 1 point and for answer c the value is 0 points. I try to make a summation of each question so that at the end a message with the final score is displayed, but I'm stuck. Here my code so far.
Thank you in advance!
const qData = [
{
question: "Question1",
a: "Yes",
b: "No",
c: "Maybe",
},
{
question: "Question2",
a: "Always",
b: "Sometimes",
c: "Never",
},
{
question: "Question3",
a: "100%",
b: "50%",
c: "0%",
}
]
const questionE1 = document.getElementById("question");
const a_text = document.getElementById("a-text");
const b_text = document.getElementById("b-text");
const c_text = document.getElementById("c-text");
const submitBtn = document.getElementById("siguiente")
let currentQuiz = 0;
loadQuiz();
function loadQuiz() {
const currentQuizData = qData[currentQuiz];
questionE1.innerText = currentQuizData.question;
a_text.innerText = currentQuizData.a;
b_text.innerText = currentQuizData.b;
c_text.innerText = currentQuizData.c;
}
submitBtn.addEventListener("click", () => {
currentQuiz++;
});
const numericalValues = new Array();
numericalValues["a"]= 2;
numericalValues["b"]= 1;
numericalValues["c"]= 0;
function getscore() {
var puntos = 0;
var answer = document.getElementById("answer");
for(var i=0; i<answer.length; i++)
{
if(answer[i]) {
puntos = numericalValues[answer[i].value];
}
}
return puntos;
};
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Quiz</title>
<link rel="stylesheet" href="style.css">
<script src="./script.js" defer></script>
</head>
<body>
<h1>Quiz</h1>
<div class="container">
<div class="score">
<h2 id="question">Question text</h2>
<ul>
<li><input type="radio" id="a" name="answer" class="answer"><label id="a-text" for="a">Question</label></li>
<li><input type="radio" id="b" name="answer" class="answer"><label id="b-text" for="b">Question</label></li>
<li><input type="radio" id="c" name="answer" class="answer"><label id="c-text" for="c">Question</label></li>
</ul>
<button id="siguiente">Next</button>
</div>
</div>
<p id="result">Final Score</p>
</body>
</html>
I've rebuild your structure of data by adding answer property to each object, otherwise there"s no way to know if the user answers the right answer!
Also checked if the user choose an answer before move to the next!
const qData = [
{
question: "Question1",
a: "Yes",
b: "No",
c: "Maybe",
answer: "a",
},
{
question: "Question2",
a: "Always",
b: "Sometimes",
c: "Never",
answer: "b",
},
{
question: "Question3",
a: "100%",
b: "50%",
c: "0%",
answer: "c",
},
];
let currInd = -1;
let rightAnswers = 0;
function renderQuestion() {
++currInd;
if (currInd != qData.length) {
const question = document.getElementById("question");
question.innerText = qData[currInd].question;
const { a, b, c } = qData[currInd];
document.getElementById("a-text").innerText = a;
document.getElementById("b-text").innerText = b;
document.getElementById("c-text").innerText = c;
} else {
document.getElementById(
"result"
).innerText = `You got ${rightAnswers} right answers, and you lost ${
qData.length - rightAnswers
} questions`;
document.querySelector(".container").style.display = "none";
document.querySelector(".result").style.display = "block";
}
}
//render first question:
renderQuestion();
document.getElementById("nextBtn").addEventListener("click", nextQuestion);
function nextQuestion() {
let options = [...document.querySelectorAll(".answer")];
let gaveAnswer =
options.map((option) => option.checked).filter(Boolean).length == 1;
let answerMapping = {
0: "a",
1: "b",
2: "c",
};
//check the answer before move to the next question
if (gaveAnswer) {
let answerInd = options
.map((option) => option.checked)
.map(Number)
.findIndex((ind) => ind == 1);
let isRightAnswer = answerMapping[answerInd] == qData[currInd].answer;
rightAnswers += isRightAnswer;
renderQuestion();
//empty the current checked option
options.forEach((option) => {
option.checked = false;
});
} else {
alert("choose an answer");
}
}
.result {
display: none;
}
<h1>Quiz</h1>
<div class="container">
<div class="score">
<h2 id="question"></h2>
<ul id="options">
<li>
<input type="radio" id="a" name="answer" class="answer" /><label
id="a-text"
for="a"
></label>
</li>
<li>
<input type="radio" id="b" name="answer" class="answer" /><label
id="b-text"
for="b"
></label>
</li>
<li>
<input type="radio" id="c" name="answer" class="answer" /><label
id="c-text"
for="c"
></label>
</li>
</ul>
<button id="nextBtn">Next</button>
</div>
</div>
<p class="result">Final Score: <span id="result"></span></p>
If you don't understand something comment it below, I'll explain to you!
Related
I've looked into the stackoverflow recommendations about posts with similar titles and nothing solved my issue. Im new to JS, im trying to make a simple multiple choice quiz. If you get it correct you score a point, if not, u don't get any but the question counter increases, the thing is after the first question everything adds double the value, here's a quick video showcasing de error: https://gyazo.com/9fbdf63508b2713992935d813f29788e pay attention to the bottom-right corner.
This is a side project and I've been stuck on it for almost 2 weeks now.. no joke. Any help is extremely appreciated, my main language is Spanish so that's the reason of the variables names. Here's the code:
let pregunta = document.getElementById('preguntafinal');
let puntaje = document.getElementById('puntaje');
let opcion1 = document.getElementById('opcion1');
let opcion2 = document.getElementById('opcion2');
let opcion3 = document.getElementById('opcion3');
let opcion4 = document.getElementById('opcion4');
let puntito1 = document.querySelector('puntito1');
let idPreg = 0;
let respSeleccionada;
let puntosTotales = 0;
let preguntasTotales = 0;
function iterarJuego() {
pregunta.innerText = arrayPreguntas[idPreg].preg;
opcion1.innerText = arrayPreguntas[idPreg].opcionuno;
opcion2.innerText = arrayPreguntas[idPreg].opciondos;
opcion3.innerText = arrayPreguntas[idPreg].opciontres;
opcion4.innerText = arrayPreguntas[idPreg].opcioncuatro;;
elegirRespuesta();
}
function elegirRespuesta() {
opcion1.addEventListener("click", asd => {
respSeleccionada = arrayPreguntas[idPreg].opcionuno;
funAnalizar(respSeleccionada);
});
opcion2.addEventListener("click", asd => {
respSeleccionada = arrayPreguntas[idPreg].opciondos;
funAnalizar(respSeleccionada);
});
opcion3.addEventListener("click", asd => {
respSeleccionada = arrayPreguntas[idPreg].opciontres;
funAnalizar(respSeleccionada);
});
opcion4.addEventListener("click", asd => {
respSeleccionada = arrayPreguntas[idPreg].opcioncuatro;
funAnalizar(respSeleccionada);
});
}
function funAnalizar() {
console.log(respSeleccionada);
console.log(arrayPreguntas[idPreg].error);
if (respSeleccionada == arrayPreguntas[idPreg].error) {
console.log("correcto");
respCorrecta(respSeleccionada);
} else if (respSeleccionada != arrayPreguntas[idPreg].error) {
console.log("incorrecto");
respIncorrecta(respSeleccionada);
}
}
function respCorrecta() {
puntosTotales++;
preguntasTotales++;
puntaje.innerText = puntosTotales + "/" + preguntasTotales;
idPreg++;
iterarJuego(idPreg);
console.log("ja");
}
function respIncorrecta() {
preguntasTotales++;
puntaje.innerText = puntosTotales + "/" + preguntasTotales;
idPreg++;
iterarJuego(idPreg);
console.log("jant");
}
arrayPreguntas = [{
idPreg: 0,
preg: "Que significa AI en Japonés?",
opcionuno: 'amor',
opciondos: 'carcel',
opciontres: 'pizza',
opcioncuatro: 'caja',
error: 'amor'
}, {
idPreg: 1,
preg: "Cual es el hiragana 'ME' ?",
opcionuno: 'ぬ',
opciondos: 'ね',
opciontres: 'ぐ',
opcioncuatro: 'め',
error: 'め'
}, {
idPreg: 2,
preg: "En hiragana: DESAYUNO , ALMUERZO , CENA ?",
opcionuno: 'ぬ',
opciondos: 'ね',
opciontres: 'ぐ',
opcioncuatro: 'め',
error: 'め'
}, {
idPreg: 3,
preg: "Como se dice madre y padre ?",
opcionuno: 'chichi hana',
opciondos: 'hana mitsu',
opciontres: 'kirei chichi',
opcioncuatro: 'undo chichi',
error: 'kirei chichi'
}, {
idPreg: 4,
preg: "Que significa きれい ?",
opcionuno: 'rey y reina',
opciondos: 'lindo y linda',
opciontres: 'hermoso y hermosa',
opcioncuatro: 'salvaje y saldro',
error: 'lindo y linda'
}]
iterarJuego();
That's the .js ..if for some reason the html is needed ill add it with an edit.
Redid everything into English, it was messy (BTW there's a button called "Tidy" in the editor) but I couldn't find the bug, I might've corrected it without being aware I had? Anyways, I liked the flow of the code so instead of giving up I made some improvements.
The terse syntax is from HTMLFormElement interface:
Figure I
// <form id="QA"> name attribute can be used as id
const QA = document.forms.QA;
// We can make a reference to all form controls in <form>
const IO = QA.elements;
// With that defined, referencing form controls is simple
IO.question // <output id='question'>
IO.next // <button id='next'>
The HTMLFormControlsCollection interface allows us to group form controls by a common name attribute and use array methods on them or extract a value of a checked or selected form control:
Figure II
// 1 of 4 <input id='optB' name='opt' type='radio' value='optB' checked>
IO.opt // HTMLCollection of all [name='opt']
[...IO.opt] // Array of all [name='opt']
IO.opt.value // Automatically gets the value of the checked [name='opt']
I replaced the 4 click handlers with one submit handler:
Figure III
// <form> is bound to the submit event
QA.onsubmit = evaluate;
function evaluate(e) {
e.preventDefault();
If you decide to handle the submit event remember to use e.preventDefault()
otherwise the will attempt to send data to a server, and the response
will kill the page.
<!DOCTYPE html>
<html lang="en">
<head>
<title></title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<style>
html {
font: 300 3ch/1.2 'Segoe UI'
}
#score {
font-size: 1.25rem;
}
#score::before {
content: 'Score: '
}
ol {
list-style: lower-latin;
margin-top: 0
}
input,
button {
font: inherit
}
li {
margin-bottom: 8px;
}
button {
display: inline-flex;
align-items: center;
padding: 0 0.5rem;
cursor: pointer
}
</style>
</head>
<body>
<main>
<form id='QA'>
<fieldset>
<legend><output id='score'></output></legend>
<output id='question'></output>
<ol>
<li>
<input id='optA' name='opt' type='radio' value='optA'>
<label for='optA'></label>
</li>
<li>
<input id='optB' name='opt' type='radio' value='optB'>
<label for='optB'></label>
</li>
<li>
<input id='optC' name='opt' type='radio' value='optC'>
<label for='optC'></label>
</li>
<li>
<input id='optD' name='opt' type='radio' value='optD'>
<label for='optD'></label>
</li>
</ol>
<menu>
<button id='next'>Next</button>
</menu>
</fieldset>
</form>
</main>
<script>
const QA = document.forms.QA;
const IO = QA.elements;
const question = IO.question;
const score = IO.score;
const opt1 = IO.optA.nextElementSibling;
const opt2 = IO.optB.nextElementSibling;
const opt3 = IO.optC.nextElementSibling;
const opt4 = IO.optD.nextElementSibling;
let qID = 0;
let totalP = 0;
let totalQ = 0;
function quiz() {
question.textContent = (qID + 1) + '. ' + qArray[qID].ques;
opt1.textContent = qArray[qID].optA;
opt2.textContent = qArray[qID].optB;
opt3.textContent = qArray[qID].optC;
opt4.textContent = qArray[qID].optD;
[...IO.opt].forEach(o => {
if (o.checked) {
o.checked = false;
}
});
}
QA.onsubmit = evaluate;
function evaluate(e) {
e.preventDefault();
let selected = IO.opt.value;
if (selected === qArray[qID].right) {
correct();
} else {
wrong();
}
}
function correct() {
totalP++;
totalQ++;
score.textContent = totalP + " / " + totalQ;
qID++;
if (qID >= qArray.length) {
return IO.next.style.display = 'none';
}
quiz();
}
function wrong() {
totalQ++;
score.textContent = totalP + " / " + totalQ;
qID++;
if (qID >= qArray.length) {
return IO.next.style.display = 'none';
}
quiz();
}
qArray = [{
qID: 0,
ques: "Que significa AI en Japonés?",
optA: 'amor',
optB: 'carcel',
optC: 'pizza',
optD: 'caja',
right: 'optA'
}, {
qID: 1,
ques: "Cual es el hiragana 'ME' ?",
optA: 'ぬ',
optB: 'ね',
optC: 'ぐ',
optD: 'め',
right: 'optD'
}, {
qID: 2,
ques: "En hiragana: DESAYUNO , ALMUERZO , CENA ?",
optA: 'ぬ',
optB: 'ね',
optC: 'ぐ',
optD: 'め',
right: 'optB'
}, {
qID: 3,
ques: "Como se dice madre y padre ?",
optA: 'chichi hana',
optB: 'hana mitsu',
optC: 'kirei chichi',
optD: 'undo chichi',
right: 'optC'
}, {
qID: 4,
ques: "Que significa きれい ?",
optA: 'rey y reina',
optB: 'lindo y linda',
optC: 'hermoso y hermosa',
optD: 'salvaje y saldro',
right: 'optB'
}];
quiz();
</script>
</body>
</html>
<script src="https://code.jquery.com/jquery-1.12.4.min.js">
var answers = ["A","C","B"],
tot = answers.length;
function getScore(){
var score = 0;
for (var i=0; i<tot; i++)
if($("input[class='question0']:checked").val()===answers[i]) //TODO add another classes like question1,question2,etc..
score += 1; // increment only
return score;
}
function returnScore(){
$('p').html('Score: ' + getScore() + '');
}
</script>
here in this line,
if($("input[class='question0']:checked").val()===answers[i]) //TODO add another classes like question1,question2,etc..
how to check for more than one classes? question+i is possible? or how to mention many classes? thanks in advance senior!
You can just format i into your string like so:
for(let i = 0; i < tot; i++) {
if($(`input[class='question${i}']:checked`).val() === answers[i])
score++;
}
In general you can use string literals like so using the backtick character `:
let variable = "value";
console.log(`A sentence containing a ${variable}`);
This is the way to select multiple classes in JQuery
$("input[class*=question]")
Try the full code
var answers = ["A", "C", "B", "D"];
var inputList = $("input[class*=question]");
inputList.change(returnScore);
function getScore() {
var score = 0;
inputList.each(function (i) {
if ($(this).val() === answers[i] && $(this).is(":checked")) score += 1;
});
return score;
}
function returnScore() {
$("p").html("Score: " + getScore() + "");
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<div>answers = ["A", "C", "B", "D"]</div>
<div>
<input class="question0" type="checkbox" id="question0" value="A"/>
<label for="question0">This is Question 0, value: A</label>
</div>
<div>
<input class="question1" type="checkbox" id="question1" value="C"/>
<label for="question1">This is Question 1, value: B</label>
</div>
<div>
<input class="question3" type="checkbox" id="question3" value="R"/>
<label for="question3">This is Question 3, value: R</label>
</div>
<div>
<input class="question4" type="checkbox" id="question4" value="F"/>
<label for="question4">This is Question 4, value: F</label>
</div>
<p></p>
I have five questions with 4 answers each on one website. Only one button should be clickable per question.
How can I do this?
new Vue({
el: '#app',
data: {
answers: {},
currentQuestion: {
examples: {
A: 'Lack zum Lackieren der Computergehäuse',
B: 'Elektrische Energie für die Montagewerkzeuge',
C: 'Silizium zur Herstellung der CPU',
D: 'Schrauben zum Befestigen von Bauteilen',
E: 'Zugekaufte Computergehäuse aus Stahlblech'
},
answers: {
'1': 'Rohstoff',
'2': 'Fremdbauteil',
'3': 'Hilfsstoff',
'4': 'Betriebsstoff'
},
rights: {
A: 3,
B: 4,
C: 1,
D: 3,
E: 2
}
}
},
methods: {
selectedOneAnswerButton(index) {
Array.from(this.answers).forEach(answer => (answer.active = false));
let answer = this.answers[index];
answer.active = !answer.active;
this.$set(this.answers, index, answer);
}
}
});
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet">
<div id="app">
<div
v-bind:key="index"
v-for="(example, index) in currentQuestion.examples"
class="row"
>
<div class="col-md-12">
<p class="p-3 mb-2 bg-dark text-white">{{ example }}</p>
</div>
<div
v-bind:key="index"
v-for="(answer, index) in currentQuestion.answers"
class="col-md-6"
>
<p>
<button
v-bind:class="{
'btn-primary': answer.active,
'btn-secondary': !answer.active
}"
v-on:click="selectedOneAnswerButton(index)"
class="btn btn-lg btn-block"
>
{{ answer }}
</button>
</p>
</div>
</div>
</div>
That worked
That worked the first time I needed it, but it didn't work the second time I asked a simple question with 4 answers ... and certainly not in the current situation with the four questions and the four possible answers.
Here is the example in JavaScript how I managed it without changing my data.
var currentQuestion = {
examples: {
"A": "Lack zum Lackieren der Computergehäuse",
"B": "Elektrische Energie für die Montagewerkzeuge",
"C": "Silizium zur Herstellung der CPU",
"D": "Schrauben zum Befestigen von Bauteilen",
"E": "Zugekaufte Computergehäuse aus Stahlblech"
},
answers: {
"1": "Rohstoff",
"2": "Fremdbauteil",
"3": "Hilfsstoff",
"4": "Betriebsstoff"
},
rights: {
"A": 3,
"B": 4,
"C": 1,
"D": 3,
"E": 2
}
};
function selectAnswer(id) {
$(id).addClass("btn-primary");
$(id).removeClass("btn-secondary");
}
function deselectAnswer(id) {
$(id).addClass("btn-secondary");
$(id).removeClass("btn-primary");
}
var root = document.getElementById("container");
var mutlipleequestionscreen = document.createElement("div");
buildMultipleQuestionScreen();
// LAYOUT
function buildMultipleQuestionScreen() {
console.log("buildMultipleQuestionScreen");
mutlipleequestionscreen.id = "multiple-question-screen";
mutlipleequestionscreen.className = "jumbotron question";
root.appendChild(mutlipleequestionscreen);
var div = document.createElement("div");
div.id = "multiple-questions";
var h2 = document.createElement("h2");
h2.textContent = "Frage ";
var span = document.createElement("span");
span.className = "multiple-question-number";
span.textContent = currentQuestion.id;
var div2 = document.createElement("div");
div2.className = "situation p-3 mb-2 bg-info text-white";
var p = document.createElement("p");
p.className = "multiple-question-situation";
p.textContent = currentQuestion.situation;
var p2 = document.createElement("p");
p2.className = "multiple-question-description";
p2.textContent = currentQuestion.description;
var p3 = document.createElement("p");
p3.className = "multiple-question-text";
p3.textContent = currentQuestion.question;
var p4 = document.createElement("p");
p4.className = "multiple-question-exercise";
p4.textContent = currentQuestion.exercise;
var p5 = document.createElement("p");
p5.className = "multiple-question-note";
p5.textContent = currentQuestion.note;
mutlipleequestionscreen.appendChild(div);
div.appendChild(h2);
h2.append(span);
div.appendChild(div2);
div2.appendChild(p);
div.appendChild(p2);
div.appendChild(p3);
div.appendChild(p4);
div.appendChild(p5);
var letter = "";
for(var i = 0; i < Object.keys(currentQuestion.examples).length; i++)
{
var row = document.createElement("div");
row.className = "row";
var div3 = document.createElement("div");
div3.className = "col-md-12";
var p6 = document.createElement("p");
p6.className = "p-3 mb-2 bg-dark text-white";
p6.textContent = Object.keys(currentQuestion.examples)[i] + " : ";
var span2 = document.createElement("span");
letter = Object.keys(currentQuestion.examples)[i];
span2.id = "multiple-question-example-" + letter.toLowerCase();
span2.textContent = currentQuestion.examples[Object.keys(currentQuestion.examples)[i]];
div.appendChild(row);
row.appendChild(div3);
div3.appendChild(p6);
p6.appendChild(span2);
var row2 = document.createElement("div");
row2.className = "row";
for(var j = 1; j <= Object.keys(currentQuestion.answers).length; j++)
{
if(j % 2 != 0)
{
div.appendChild(row2);
}
var div4 = document.createElement("div");
div4.className = "col-md-6";
var p7 = document.createElement("p");
var button = document.createElement("button");
button.id = "multiple-question-answer-" + letter.toLowerCase() + "-" + j + "-btn"
button.className = "answer answer-btn answer-" + letter.toLowerCase() + "-btn answer-" + j + "-btn btn btn-secondary btn-lg btn-block";
var span3 = document.createElement("span");
span3.className = "multiple-question-answer-" + j;
span3.textContent = Object.keys(currentQuestion.answers)[j - 1] + ": " + currentQuestion.answers[j];
button.addEventListener("click", function() {
selectAnswer(this);
var letterTmp = this.id.split('-')[3];
$(".answer-" + letterTmp + "-btn").not(this).each(function() {
deselectAnswer(this);
});
console.log(this.id);
});
row2.appendChild(div4);
div4.appendChild(p7);
p7.appendChild(button);
button.appendChild(span3);
}
}
var row3 = document.createElement("div");
row3.className = "row";
var div5 = document.createElement("div");
div5.className ="col-md-10";
var div6 = document.createElement("div");
div6.className = "col-md-2";
var p8 = document.createElement("p");
var button2 = document.createElement("button");
button2.id = "multiple-question-answer-commit-btn";
button2.className = "answer-commit-btn btn btn-primary btn-lg btn-block";
var span4 = document.createElement("span");
span4.className = "multiple-question-commit-text";
span4.textContent = "Antworten";
// MULTIPLE QUESTION ANTWORTEN BUTTON
button2.addEventListener("click", function() {
// IN DEN GLOBALEN EINSTELLUNGEN
// .answer-commit-btn
answerCommitButton();
});
var p9 = document.createElement("p");
var button3 = document.createElement("button");
button3.id ="multiple-question-continue-btn";
button3.className = "continue-btn btn btn-primary btn-lg btn-block";
button3.style = "display: none;";
var span5 = document.createElement("span");
span5.textContent = "Weiter";
// MULTIPLE QUESTION WEITER BUTTON
button3.addEventListener("click", function() {
var node = document.getElementById("container");
var child = document.getElementById("multiple-question-screen");
var child2 = document.getElementById("multiple-questions");
node.removeChild(child);
child.removeChild(child2);
// IN DEN GLOBALEN EINSTELLUNGEN
continueButton();
});
div.appendChild(row3);
row3.appendChild(div5);
row3.appendChild(div6);
div6.appendChild(p8);
p8.appendChild(button2);
button2.appendChild(span4);
div6.appendChild(p9);
p9.appendChild(button3);
button3.appendChild(span5);
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
<!-- Bootstrap -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
</head>
<body>
<div id="container">
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="example.js"></script>
</body>
</html>
It is possible to do this in VUE.JS without changing my data?
The issue is your answers are a string, but you're treating it like an object. Trying to add the active property to it which is not going to work.
Another problem is that if you modify the answers, it will impact all the questions, instead of just the one. Since they all share the same array.
Instead i would modify your examples object, to contain objects instead of strings.
This object would contain the question and the answer the user picks.
That way you will have a specific answer for each question, and the user can only pick one since it will overwrite the old value.
Note: #click is shorthand for v-on:click, and :class is shorthand for v-bind:class
Option 1:
new Vue({
el: '#app',
data: {
answers: {},
currentQuestion: {
examples: {
A: {
question: 'Lack zum Lackieren der Computergehäuse',
pickedAnswer: null
},
B: {
question: 'Elektrische Energie für die Montagewerkzeuge',
pickedAnswer: null
},
C: {
question: 'Silizium zur Herstellung der CPU',
pickedAnswer: null
},
D: {
question: 'Schrauben zum Befestigen von Bauteilen',
pickedAnswer: null
},
E: {
question: 'Zugekaufte Computergehäuse aus Stahlblech',
pickedAnswer: null
}
},
answers: {
'1': 'Rohstoff',
'2': 'Fremdbauteil',
'3': 'Hilfsstoff',
'4': 'Betriebsstoff'
},
rights: {
A: 3,
B: 4,
C: 1,
D: 3,
E: 2
}
}
}
});
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet">
<div id="app">
<div
:key="index"
v-for="(example, index) in currentQuestion.examples"
class="row"
>
<div class="col-md-12">
<p class="p-3 mb-2 bg-dark text-white">{{ example.question }}</p>
</div>
<div
:key="index"
v-for="(answer, index, key) in currentQuestion.answers"
class="col-md-6"
>
<p>
<button
:class="{
'btn-primary': example.pickedAnswer == key,
'btn-secondary': example.pickedAnswer != key
}"
#click="example.pickedAnswer = key"
class="btn btn-lg btn-block"
>
{{ answer }}
</button>
</p>
</div>
</div>
</div>
Instead of converting your examples to objects, you can add a new property to your currentQuestion object. I've called it pickedAnswers in the example, this object will contain which answers the user has picked.
Option 2:
new Vue({
el: '#app',
data: {
answers: {},
currentQuestion: {
examples: {
A: 'Lack zum Lackieren der Computergehäuse',
B: 'Elektrische Energie für die Montagewerkzeuge',
C: 'Silizium zur Herstellung der CPU',
D: 'Schrauben zum Befestigen von Bauteilen',
E: 'Zugekaufte Computergehäuse aus Stahlblech'
},
pickedAnswers: {
A: null,
B: null,
C: null,
D: null,
E: null,
},
answers: {
'1': 'Rohstoff',
'2': 'Fremdbauteil',
'3': 'Hilfsstoff',
'4': 'Betriebsstoff'
},
rights: {
A: 3,
B: 4,
C: 1,
D: 3,
E: 2
}
}
}
});
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet">
<div id="app">
<div
:key="index"
v-for="(example, questionKey, index) in currentQuestion.examples"
class="row"
>
<div class="col-md-12">
<p class="p-3 mb-2 bg-dark text-white">{{ example }}</p>
</div>
<div
:key="index"
v-for="(answer, key) in currentQuestion.answers"
class="col-md-6"
>
<p>
<button
:class="{
'btn-primary': currentQuestion.pickedAnswers[questionKey] == key,
'btn-secondary': currentQuestion.pickedAnswers[questionKey] != key
}"
#click="currentQuestion.pickedAnswers[questionKey] = key"
class="btn btn-lg btn-block"
>
{{ answer }}
</button>
</p>
</div>
</div>
</div>
I created an array of objects with different properties but I am having problem displaying each properties of my object on the webpage. I have tried but I don't know where the problem is.
I have tried to access the objects individually but still not working please check the problem
//Get the id's of all elements
const intro = document.getElementById("introduction");
const continued = document.getElementById("continue");
const name = document.getElementById("name").value;
const wel = document.getElementById("wel")
const startt = document.getElementById("startt");
const start = document.getElementById("start");
const quiz = document.getElementById("quiz");
const question = document.getElementById("question");
const qImg = document.getElementById("qImg");
const choiceA = document.getElementById("A");
const choiceB = document.getElementById("B");
const choiceC = document.getElementById("C");
const choiceD = document.getElementById("D");
const counter = document.getElementById("counter");
const timeGauge = document.getElementById("timeGauge");
const progress = document.getElementById("progress");
const scoreDiv = document.getElementById("scoreContainer");
//Event listeners
continued.addEventListener('click', continueAfterIntro);
start.addEventListener('click', startQuiz);
//variable declarations
const lastQuestion = questions.length - 1;
var runningQuestion = 0;
var secs = 0;
var mins = 0;
var hrs = 0;
const questionTime = 60; // 60s
const gaugeWidth = 180; // 180px
const gaugeUnit = gaugeWidth / questionTime;
let TIMER;
let score = 0;
//Array object declaration
let questions = [{
question: "Who is the president Nigeria?",
choiceA: "Muhamadu Buhari",
choiceB: "Osibajo",
choiceC: "Obasanjo",
choiceD: "Green,Red,Green",
correct: "A"
}, {
question: "Who is the governor of oyo state?",
choiceA: "Abiola Ajumobi",
choiceB: "Seyi makinde",
choiceC: "Alao Akala",
choiceD: "Green,Red,Green",
correct: "B"
}, {
question: "What are the colors of the Nigerian Flag?",
choiceA: "Green,White,Blue",
choiceB: "Blue,White,Green",
choiceC: "Green,White,Green",
choiceD: "Green,Red,Green",
correct: "C"
}];
function continueAfterIntro() {
intro.style.display = 'none';
startt.style.display = 'block';
wel.innerHTML = `Hi ${name}`;
}
function renderQuestion() {
let q = questions[runningQuestion];
question.innerHTML = "<p>" + q.question + "</p>";
choiceA.innerHTML = q.choiceA;
choiceB.innerHTML = q.choiceB;
choiceC.innerHTML = q.choiceC;
}
function startQuiz() {
startt.style.display = "none";
quiz.style.display = "block";
renderQuestion();
}
<div id="container">
<div class="" id="introduction">
<div id="pimg"><img src="pic/thumbs.png" alt="WELCOME FACE"></div>
<div id="para1">
<p>Hey there i'm AFO by name whats yours</p>
</div>
<div id="name-button">
<span id="iName"><input type="text" id="name" placeholder="Type Your Name Here"></span>
<span id="continue"><input type="button" value="Continue" id="continue"></span>
</div>
</div>
<div id="startt" style="display: none">
<p id="wel"></p>
<div id="start">Start Quiz!</div>
</div>
<div id="quiz" style="display: none">
<div id="question"></div>
<div id="choices">
A.
<div class="choice" id="A" onclick="checkAnswer('A')"></div>
B.
<div class="choice" id="B" onclick="checkAnswer('B')"></div>
C.
<div class="choice" id="C" onclick="checkAnswer('C')"></div>
D.
<div class="choice" id="D" onclick="checkAnswer('D')"></div>
</div>
<div id="timer">
<div id="counter"></div>
<div id="btimeGauge"></div>
<div id="timeGauge"></div>
</div>
<div id="progress"></div>
</div>
<div id="scoreContainer" style="display: none"></div>
</div>
The function renderQuestion should display the questions and the choices on the webpage
When i run your project i got ReferenceError.
Uncaught ReferenceError: Cannot access 'questions' before initialization
That means you can't play around with Questions Array before initialization. For example:
const questionsLength = questions.length; // REFERENCE ERROR.
const questions = ['a', 'b', 'c'];
console.log(questionsLength);
Declare Questions Array before you inspect length:
const questions = ['a', 'b', 'c'];
const questionsLength = questions.length;
console.log(questionsLenght) // Returns 3
Working example:
//Get the id's of all elements
const intro = document.getElementById("introduction");
const continued = document.getElementById("continue");
const name = document.getElementById("name").value;
const wel = document.getElementById("wel")
const startt = document.getElementById("startt");
const start = document.getElementById("start");
const quiz = document.getElementById("quiz");
const question = document.getElementById("question");
const qImg = document.getElementById("qImg");
const choiceA = document.getElementById("A");
const choiceB = document.getElementById("B");
const choiceC = document.getElementById("C");
const choiceD = document.getElementById("D");
const counter = document.getElementById("counter");
const timeGauge = document.getElementById("timeGauge");
const progress = document.getElementById("progress");
const scoreDiv = document.getElementById("scoreContainer");
//Event listeners
continued.addEventListener('click',continueAfterIntro);
start.addEventListener('click',startQuiz);
//Array object declaration
let questions = [
{
question : "Who is the president Nigeria?",
choiceA : "Muhamadu Buhari",
choiceB : "Osibajo",
choiceC : "Obasanjo",
choiceD : "Green,Red,Green",
correct : "A"
},{
question : "Who is the governor of oyo state?",
choiceA : "Abiola Ajumobi",
choiceB : "Seyi makinde",
choiceC : "Alao Akala",
choiceD : "Green,Red,Green",
correct : "B"
},{
question : "What are the colors of the Nigerian Flag?",
choiceA : "Green,White,Blue",
choiceB : "Blue,White,Green",
choiceC : "Green,White,Green",
choiceD : "Green,Red,Green",
correct : "C"
}
];
//variable declarations
const lastQuestion = questions.length - 1;
var runningQuestion = 0;
var secs = 0;
var mins = 0;
var hrs = 0;
const questionTime = 60; // 60s
const gaugeWidth = 180; // 180px
const gaugeUnit = gaugeWidth / questionTime;
let TIMER;
let score = 0;
function continueAfterIntro(){
intro.style.display = 'none';
startt.style.display = 'block';
wel.innerHTML = `Hi ${name}`;
}
function renderQuestion(){
let q = questions[runningQuestion];
question.innerHTML = "<p>"+ q.question +"</p>";
choiceA.innerHTML = q.choiceA;
choiceB.innerHTML = q.choiceB;
choiceC.innerHTML = q.choiceC;
}
function startQuiz(){
startt.style.display = "none";
quiz.style.display = "block";
renderQuestion();
}
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="quiz.css">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id="container">
<div class="" id="introduction">
<div id="pimg"><img src="pic/thumbs.png" alt="WELCOME FACE"></div>
<div id="para1"><p>Hey there i'm AFO by name whats yours</p> </div>
<div id="name-button">
<span id="iName"><input type="text" id="name" placeholder="Type Your Name Here"></span>
<span id="continue"><input type="button" value="Continue" id="continue"></span>
</div>
</div>
<div id="startt" style="display: none">
<p id="wel"></p>
<div id="start" >Start Quiz!</div>
</div>
<div id="quiz" style="display: none">
<div id="question"></div>
<div id="choices">
A.<div class="choice" id="A" onclick="checkAnswer('A')"></div>
B.<div class="choice" id="B" onclick="checkAnswer('B')"></div>
C.<div class="choice" id="C" onclick="checkAnswer('C')"></div>
D.<div class="choice" id="D" onclick="checkAnswer('D')"></div>
</div>
<div id="timer">
<div id="counter"></div>
<div id="btimeGauge"></div>
<div id="timeGauge"></div>
</div>
<div id="progress"></div>
</div>
<div id="scoreContainer" style="display: none"></div>
</div>
</body>
</html>
What ReferenceError mean MDN#ReferenceError
I'm writing a little exercise where I move things from one "select" to another. Works great! I don't have multi-select yet, but I'll do that later. More importantly, I thought I would add counters so that values associated with the "options" could be added up. That function doesn't seem to be working. When I move things from one column to the other the labels meant for the summed values are filled with the text 0[object Object]. I'm sure this is on account of a pretty obvious mistake, but I lack the vocabulary to articulate the problem in any other terms. Please teach me? :-)
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<style type="text/css">
#selectSource {
width: 320px;
}
#selectTarget {
width: 320px;
}
#wgtsum {
width: 22px;
}
#cubesum {
width: 22px;
}
</style>
<title>Loader</title>
<script>
var data;
var sumCube = 0;
var sumWgt = 0;
window.onload = function () {
//Add way to load JSON data from a text file or something
var load = document.getElementById('selectSource')
data = [
{ num: "1", cube: 6, wgt: 2, title: "num: 1 cube: 6 wgt: 2" },
{ num: "2", cube: 4, wgt: 4, title: "num: 2 cube: 4 wgt: 4" },
{ num: "3", cube: 2, wgt: 6, title: "num: 3 cube: 2 wgt: 6" }
];
for (i = 0; i < data.length; i++) {
load.options.add(new Option(data[i].title, data[i].num));
}
}
function sum() {
var sumTarget = document.getElementById('selectTarget');
for (i = 0; i < data.length; i++) {
for (o = 0; o < sumTarget.length; o++) {
if (sumTarget[o].value = data[i].value) {
sumCube = sumCube + data[i].cube;
sumWgt = sumWgt + data[i].wgt;
}
}
}
document.getElementById("cubesum").setAttribute("value", sumCube);
document.getElementById("wgtsum").setAttribute("value", sumWgt);
}
function move(from, to) {
selected = from.options.selectedIndex;
to.options.add(new Option(from.options[selected].text, from.options[selected].value));
from.options.remove(selected);
sum();
}
</script>
</head>
<body>
<form>
<select id="selectTarget" size="4">
</select>
<button type="button" onclick="move(this.form.selectSource, this.form.selectTarget)" style="width: 58px">To Target</button>
<button type="button" onclick="move(this.form.selectTarget, this.form.selectSource)" style="width: 58px">To Source</button>
<select id="selectSource" size="4">
</select>
<input value="0" type="text" id="cubesum" size="5"/>
<input value="0" type="text" id="wgtsum" size="5"/>
</form>
</body>
</html>
In your "sum() " function it looks like your if statement should be doing a comparison == instead of an assignment =.