How can I add Images to JavaScript quiz app - javascript

I was trying to add images for a JavaScript quiz app but I tried everything, adding "img src" attribute in different ways but nothing seems to work...please help it's for a project that needs to be done. here is my code...
const quizData = [{
question: "Which language runs in a web browser?",
a: "Java",
b: "C",
c: "Python",
d: "javascript",
correct: "d",
},
{
question: "What does CSS stand for?",
a: "Central Style Sheets",
b: "Cascading Style Sheets",
c: "Cascading Simple Sheets",
d: "Cars SUVs Sailboats",
correct: "b",
},
{
question: "What does HTML stand for?",
a: "Hypertext Markup Language",
b: "Hypertext Markdown Language",
c: "Hyperloop Machine Language",
d: "Helicopters Terminals Motorboats Lamborginis",
correct: "a",
},
{
question: "What year was JavaScript launched?",
a: "1996",
b: "1995",
c: "1994",
d: "none of the above",
correct: "b",
},
{
question: "Is this a test run?",
a: "yes it is",
b: "why do you care?",
c: "stop asking",
d: "I don't know",
correct: "d",
},
{
question: "where do you see yourself in years?",
a: "In the gutter",
b: "Forbes magazine",
c: "Simple guy",
d: "outside the country",
correct: "b",
},
];
const quiz = document.getElementById('quiz')
const answerEls = document.querySelectorAll('.answer')
const questionEl = 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 d_text = document.getElementById('d_text')
const submitBtn = document.getElementById('submit')
let currentQuiz = 0
let score = 0
loadQuiz()
function loadQuiz() {
deselectAnswers()
const currentQuizData = quizData[currentQuiz]
questionEl.innerText = currentQuizData.question
a_text.innerText = currentQuizData.a
b_text.innerText = currentQuizData.b
c_text.innerText = currentQuizData.c
d_text.innerText = currentQuizData.d
}
function deselectAnswers() {
answerEls.forEach(answerEl => answerEl.checked = false)
}
function getSelected() {
let answer
answerEls.forEach(answerEl => {
if (answerEl.checked) {
answer = answerEl.id
}
})
return answer
}
submitBtn.addEventListener('click', () => {
const answer = getSelected()
if (answer) {
if (answer === quizData[currentQuiz].correct) {
score++
}
currentQuiz++
if (currentQuiz < quizData.length) {
loadQuiz()
} else {
quiz.innerHTML = `
<h2>You answered ${score}/${quizData.length} questions correctly</h2>
<button onclick="location.reload()">Reload</button>
`
}
}
})
<div class="quiz-container" id="quiz">
<div class="quiz-header">
<h2 id="question">Question Text</h2>
<ul>
<li> <input type="radio" name="answer" id="a" class="answer"> <label for="a" id="a_text">Answer</label> </li>
<li> <input type="radio" name="answer" id="b" class="answer"> <label for="b" id="b_text">Answer</label> </li>
</ul>
</div>
<button id="submit">Submit</button>
</div>
I want to add different images whenever the questions changes.How can I do that?

I'm assuming you want the image to appear with the innerHTML at the end of the quiz. Maybe the URL you're using isn't absolute? I've added an image with an absolute URL and it works:
const quizData = [{
question: "Which language runs in a web browser?", correct: "d",
a: "Java", b: "C", c: "Python", d: "javascript",
img: "https://placekitten.com/200/200"
},
{
question: "What does CSS stand for?", correct: "b",
a: "Central Style Sheets", b: "Cascading Style Sheets", c: "Cascading Simple Sheets", d: "Cars SUVs Sailboats",
img: "https://placekitten.com/300/200"
},
{
question: "What does HTML stand for?", correct: "a",
a: "Hypertext Markup Language", b: "Hypertext Markdown Language", c: "Hyperloop Machine Language", d: "Helicopters Terminals Motorboats Lamborginis",
img: "https://placekitten.com/200/300"
},
{
question: "What year was JavaScript launched?", correct: "b",
a: "1996", b: "1995", c: "1994", d: "none of the above",
img: "https://placekitten.com/400/200"
},
{
question: "Is this a test run?", correct: "d",
a: "yes it is", b: "why do you care?", c: "stop asking", d: "I don't know",
img: "https://placekitten.com/200/400"
},
{
question: "where do you see yourself in years?", correct: "b",
a: "In the gutter", b: "Forbes magazine", c: "Simple guy", d: "outside the country",
img: "https://placekitten.com/500/200"
}];
const quiz = document.getElementById('quiz')
const answerEls = document.querySelectorAll('.answer')
const questionEl = 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 d_text = document.getElementById('d_text')
const submitBtn = document.getElementById('submit')
const questImg = document.querySelector('.question-container > img')
let currentQuiz = 0
let score = 0
loadQuiz()
function loadQuiz() {
deselectAnswers()
const currentQuizData = quizData[currentQuiz]
questionEl.innerText = currentQuizData.question
a_text.innerText = currentQuizData.a
b_text.innerText = currentQuizData.b
c_text.innerText = currentQuizData.c
d_text.innerText = currentQuizData.d
questImg.src = currentQuizData.img
}
function deselectAnswers() {
answerEls.forEach(answerEl => answerEl.checked = false)
}
function getSelected() {
let answer
answerEls.forEach(answerEl => {
if (answerEl.checked) {
answer = answerEl.id
}
})
return answer
}
submitBtn.addEventListener('click', () => {
const answer = getSelected()
if (answer) {
if (answer === quizData[currentQuiz].correct) {
score++
}
currentQuiz++;
if(currentQuiz < quizData.length) {
loadQuiz()
} else {
quiz.innerHTML = `
<h2>You answered ${score}/${quizData.length} questions correctly</h2>
<img src="https://placekitten.com/200/200">
<button onclick="location.reload()">Reload</button>
`
}
}
})
.question-container{
display: flex;
align-items: flex-end;
}
.question-container > img{
width: 100px;
margin-left: 10px;
}
<div id="quiz"></div>
<div class="question-container">
<div id="question"></div>
<img />
</div>
<input id="a" type="checkbox" class="answer" />
<label id="a_text"></label>
<br>
<input id="b" type="checkbox" class="answer" />
<label id="b_text"></label>
<br>
<input id="c" type="checkbox" class="answer" />
<label id="c_text"></label>
<br>
<input id="d" type="checkbox" class="answer" />
<label id="d_text"></label>
<br><br>
<button id="submit">Submit</button>

Related

Javascrpt ; reshape a dataset (read in as a 2D array) to be indexed by rows instead of columns

I'm trying to format my dataset so it can be used by danfjo.js which is formatted as the following
json_data = [{ A: 0.4612, B: 4.28283, C: -1.509, D: -1.1352 },
{ A: 0.5112, B: -0.22863, C: -3.39059, D: 1.1632 },
{ A: 0.6911, B: -0.82863, C: -1.5059, D: 2.1352 },
{ A: 0.4692, B: -1.28863, C: 4.5059, D: 4.1632 }]
df = new dfd.DataFrame(json_data)
df.print()
My POST request sends back a dataframe in the following form.
data
'A' : {0:'0.4612', 1:'0.5112',...
'B' : {0:'4.28283', 1:'-0.22863', ...
I'm unfamilar with the javascript language. What term would you use for this reshape and how would you go about it?
The API POST data provided in the question is invalid as well as incomplete. It could be either an object or an array of objects or something else. In either of the two cases (first being formB, and second being formC in the snippet below), the code will generate an array (which matches the array being assigned to the variable json_data in the question abouve) when user presses "y" at the prompt.
const myTransform = (obj, retArr = false) => {
const res = structuredClone(
Array.isArray(obj)
? {...obj}
: obj
);
const colKeys = [...new Set(
Object.values(res)
.flatMap(ob => (
Object.keys(ob)
))
)];
const rowKeys = [...new Set(Object.keys(res))];
const result = (
Object.fromEntries(colKeys.map(c => ([
[c], Object.fromEntries(rowKeys.map(r => ([
[r], res[r][c]
])))
])))
);
return (
retArr
? Object.values(result)
: result
);
};
const formA = [{
A: 0.4612,
B: 4.28283,
C: -1.509,
D: -1.1352
},
{
A: 0.5112,
B: -0.22863,
C: -3.39059,
D: 1.1632
},
{
A: 0.6911,
B: -0.82863,
C: -1.5059,
D: 2.1352
},
{
A: 0.4692,
B: -1.28863,
C: 4.5059,
D: 4.1632
}
];
const formB = {
"A": {
"0": 0.4612,
"1": 0.5112,
"2": 0.6911,
"3": 0.4692
},
"B": {
"0": 4.28283,
"1": -0.22863,
"2": -0.82863,
"3": -1.28863
},
"C": {
"0": -1.509,
"1": -3.39059,
"2": -1.5059,
"3": 4.5059
},
"D": {
"0": -1.1352,
"1": 1.1632,
"2": 2.1352,
"3": 4.1632
}
};
const formC = [{
"A": {
"0": 0.4612,
"1": 0.5112,
"2": 0.6911,
"3": 0.4692
}},{
"B": {
"0": 4.28283,
"1": -0.22863,
"2": -0.82863,
"3": -1.28863
}},{
"C": {
"0": -1.509,
"1": -3.39059,
"2": -1.5059,
"3": 4.5059
}},{
"D": {
"0": -1.1352,
"1": 1.1632,
"2": 2.1352,
"3": 4.1632
}
}];
console.log(
myTransform(
formB,
prompt('Press "y" for array')
.toString()
.toLowerCase()
=== 'y'
)
);
.as-console-wrapper { max-height: 100% !important; top: 0 }

How to update a variable value returned from a function

This is my Quiz code for javascript:
"use strict"
const questions = [
{
question: "whats the full form of HTML",
answers: {
a: "Hello Text My Language",
b: "Hyper text Main Language",
c: "Hyper Text Markup Language",
d: "Hi There My Luck",
},
correctAnswer:"ent-c",
},
{
question: "whats the full form of CSS",
answers: {
a: "Cascading Style Sheet",
b: "City Site Section",
c: "Cyber Section Stand",
d: "CycleStand Section",
},
correctAnswer:"ent-a",
},
{
question: "whats the full form of JSON",
answers: {
a: "Jest Oriented Note",
b: "JavaScript Object Notation",
c: "Javascript Organised Node",
d: "Joomla Of Node",
},
correctAnswer:"ent-b",
},
{
question: "whats the full form of SQL",
answers: {
a: "Super Query Language",
b: "Sorted Queue Line",
c: "Superior Query Language",
d: "Structured Query Language",
},
correctAnswer:"ent-d",
},
];
let quest = document.querySelector('.question');
let quizLIst = document.querySelector('.quiz');
const btn = document.querySelector('.submitBtn');
const scoreDiv = document.querySelector('.scoreCard');
let currentQuestion = 0;
let score=0;
const loadQuestion = () =>{
quest.innerText="";
quizLIst.innerHTML="";
console.log(questions[currentQuestion].question);
quest.innerText = questions[currentQuestion].question;
const ansEntries = Object.entries(questions[currentQuestion].answers);
for (const [getQ, getA] of ansEntries) {
quizLIst.innerHTML += `
<li><input type="radio" class="ansOptions" id="ent-${getQ}" name="ans" value="${getA}"/><label for="${getA}">${getA}</label></</li>
`;
}
}
loadQuestion();
const allAnss = document.querySelectorAll('.ansOptions');
let getCheckedAnswer = () =>{
let answer="";
allAnss.forEach((currAns) =>{
if(currAns.checked){
answer = currAns.id;
}
});
return answer;
}
btn.addEventListener('click', ()=> {
let checkedAnswer = getCheckedAnswer();
console.log("checked answer is ", checkedAnswer);
if(checkedAnswer === questions[currentQuestion].correctAnswer){
console.log("right");
score++;
}
else{
console.log("wrong");
}
currentQuestion++;
if(currentQuestion <= questions.length){
loadQuestion();
}
})
But somehow checkedAnswer variable is not getting updated. After first question, checkedAnswer value is not getting empty, therefore my next answers are stuck with the first answer. where can i empty the checkedAnswer value in the code, i tried doing it, but nothing seemed to be working
You need to get the current options contained in your .ansOptions. So you need to update getCheckedAnswer() for each question, as allAnss is still containing the old NodeList from the first question's options.
"use strict"
const questions = [
{
question: "whats the full form of HTML",
answers: {
a: "Hello Text My Language",
b: "Hyper text Main Language",
c: "Hyper Text Markup Language",
d: "Hi There My Luck",
},
correctAnswer:"ent-c",
},
{
question: "whats the full form of CSS",
answers: {
a: "Cascading Style Sheet",
b: "City Site Section",
c: "Cyber Section Stand",
d: "CycleStand Section",
},
correctAnswer:"ent-a",
},
{
question: "whats the full form of JSON",
answers: {
a: "Jest Oriented Note",
b: "JavaScript Object Notation",
c: "Javascript Organised Node",
d: "Joomla Of Node",
},
correctAnswer:"ent-b",
},
{
question: "whats the full form of SQL",
answers: {
a: "Super Query Language",
b: "Sorted Queue Line",
c: "Superior Query Language",
d: "Structured Query Language",
},
correctAnswer:"ent-d",
},
];
let quest = document.querySelector('.question');
let quizLIst = document.querySelector('.quiz');
const btn = document.querySelector('.submitBtn');
const scoreDiv = document.querySelector('.scoreCard');
let currentQuestion = 0;
let score=0;
const loadQuestion = () =>{
quest.innerText="";
quizLIst.innerHTML="";
console.log(questions[currentQuestion].question);
quest.innerText = questions[currentQuestion].question;
const ansEntries = Object.entries(questions[currentQuestion].answers);
for (const [getQ, getA] of ansEntries) {
quizLIst.innerHTML += `
<li><input type="radio" class="ansOptions" id="ent-${getQ}" name="ans" value="${getA}"/><label for="${getA}">${getA}</label></</li>
`;
}
}
loadQuestion();
let getCheckedAnswer = () =>{
const allAnss = document.querySelectorAll('.ansOptions')
let answer="";
allAnss.forEach((currAns) =>{
if(currAns.checked){
answer = currAns.id;
}
});
return answer;
}
btn.addEventListener('click', ()=> {
let checkedAnswer = getCheckedAnswer();
if(checkedAnswer === questions[currentQuestion].correctAnswer){
console.log("right");
++score;
} else {
console.log("wrong");
}
currentQuestion++;
if(currentQuestion < questions.length){
loadQuestion();
}
document.querySelector('.scoreCard').innerText = 'Your score is ' + score + '.';
})
<div class="scoreCard"></div>
<div class="question"></div>
<div class="quiz"></div>
<button class="submitBtn">answer</button>

TypeError: "TypeError: function name is not a function at HTMLButtonElement.onclick (/:2:54)"

I'm trying to build a really simple survey on Javascript but I keep getting this error "TypeError: startSurvey is not a function at HTMLButtonElement.onclick (/:2:54)" I would really appreciate if anybody can help me solve this error or provide any further feedback and suggestions.
Here's my HTML code:
<div class="surveysection">
<button onclick="startSurvey()" id="startSurvey">Start Survey</button>
<div id="questions"></div>
</div>
<script>
Here's my script file:
var ourQuestions = [
{
question:'While naturally occurring wildfires can benefit ecosystems, unnatural blazes started by uncaring and negligent humans can do great harm and cause many deaths. What percentage of wildfires do you think are started by humans?',
answers: {
a: '10-15%',
b: '85-90%',
c: '45-50%',
d: '25-30%'
},
correctAnswer: 'b'
},
{
question: 'If you have lit a campfire before, how did you extinguish it?',
answers: {
a: 'I did not extinguish it and waited for it to die on its own',
b: 'I extinguished the campfire with a bucket of water and made sure it was fully extinguished.',
c: 'I have never lit a campfire before.',
d: 'uhhh'
},
correctAnswer: 'b'
},
{
question: 'What are the two most common reasons that forest fires start?',
answers: {
a: 'Lightning and human negligence',
b: 'Spontaneous combustion and erosion',
c: 'Animals igniting flames and overcrowded bushlands',
d: 'uhhh'
},
correctAnswer: 'a'
},
{
question: 'What time of the year do most forest fires occur?',
answers: {
a: 'Summer',
b: 'Spring',
c: 'Fall',
d: 'Winter'
},
correctAnswer: 'a'
},
{
question: 'How fast do you think forest fires spread?',
answers: {
a: '10.8 km/h',
b: '6.4 km/h',
c: '22.2 km/h',
d: '3.2 km/h'
},
correctAnswer: 'a'
},
{
question: 'What do forest fires need in order to burn?',
answers: {
a: 'Water',
b: 'High humidity',
c: 'Fuel',
d: 'Clear weather'
},
correctAnswer: 'c'
},
{
question: 'What is one of the main toxic gases present in forest fire smoke?',
answers: {
a: 'Osmium tetroxide',
b: 'Disulfur decafluoride',
c: 'Tungsten hexafluoride ',
d: 'carbon monoxide'
},
correctAnswer: 'd'
},
{
question: 'What natural disasters could be caused as a consequence of a destructive forest fire?',
answers: {
a: 'Erosion, flash flooding and landslides',
b: 'Tornadoes',
c: 'Snow',
d: 'Tsunami and earthquakes'
},
correctAnswer: 'a'
},
{
question: 'What major factor determines a forest fire’s behaviour?',
answers: {
a: 'Amount of water vapour in air',
b: 'Density of Forests',
c: 'Wind',
d: 'Hours of sunlight'
},
correctAnswer: 'c'
}
];
function startSurvey(){
var i;
var j;
var k;
for(i=0; i<ourQuestions.length; i++){
document.getElementById("questions").innerHTML +='<form id="question">Q'+(i+1)+': '+ ourQuestions[i].question;
for(j=0; j<ourQuestions[i].answers.length; j++){
document.forms[i].innerHTML += '</div><div class="answer"><input name="q1" value="'+ ourQuestions[i].answers[j] +'" id="value4" type="checkbox" />' + ourQuestions[i].answers[j] + '<br/>';
}
document.getElementById("questions").innerHTML +='</form><br/><br/>';
}
document.getElementById("questions").innerHTML += '<button onclick="solveQuiz()">Solve Quiz</button>';
}
function solveSurvey(){
var x;
var txt = ' ';
var i = 0;
var correct = 0;
for(i = 0; i < document.forms.length;i++) {
x = document.forms[i];
for(j = 0; j<x.length; j++){
if(x[j].checked) {
correctAnswer = ourQuestions[i].correctAnswer;
if(x[j].value == ourQuestions[i].answers[correctAnswer]){
correct += 1;
}
}
}
}
document.getElementById("questions").innerHTML += 'Correct answers: '+ correct;
}
document.forms[i].innerHTML += '</div><div class="answer"><input name="q1" value="'+ ourQuestions[i].answers[j] +'" id="value4" type="radio" />' + ourQuestions[i].answers[j] + '<br/>';
Looks like your id and function are the same name, below I changed the function name to start();. - This alone will probably fix your problem.
Additionally it looks like i is not defined here:
document.forms[i].innerHTML += '</div><div class="answer"><input name="q1" value="'+ ourQuestions[i].answers[j] +'" id="value4" type="radio" />' + ourQuestions[i].answers[j] + '<br/>';
You might want to fix that.
var ourQuestions = [
{
question:'While naturally occurring wildfires can benefit ecosystems, unnatural blazes started by uncaring and negligent humans can do great harm and cause many deaths. What percentage of wildfires do you think are started by humans?',
answers: {
a: '10-15%',
b: '85-90%',
c: '45-50%',
d: '25-30%'
},
correctAnswer: 'b'
},
{
question: 'If you have lit a campfire before, how did you extinguish it?',
answers: {
a: 'I did not extinguish it and waited for it to die on its own',
b: 'I extinguished the campfire with a bucket of water and made sure it was fully extinguished.',
c: 'I have never lit a campfire before.',
d: 'uhhh'
},
correctAnswer: 'b'
},
{
question: 'What are the two most common reasons that forest fires start?',
answers: {
a: 'Lightning and human negligence',
b: 'Spontaneous combustion and erosion',
c: 'Animals igniting flames and overcrowded bushlands',
d: 'uhhh'
},
correctAnswer: 'a'
},
{
question: 'What time of the year do most forest fires occur?',
answers: {
a: 'Summer',
b: 'Spring',
c: 'Fall',
d: 'Winter'
},
correctAnswer: 'a'
},
{
question: 'How fast do you think forest fires spread?',
answers: {
a: '10.8 km/h',
b: '6.4 km/h',
c: '22.2 km/h',
d: '3.2 km/h'
},
correctAnswer: 'a'
},
{
question: 'What do forest fires need in order to burn?',
answers: {
a: 'Water',
b: 'High humidity',
c: 'Fuel',
d: 'Clear weather'
},
correctAnswer: 'c'
},
{
question: 'What is one of the main toxic gases present in forest fire smoke?',
answers: {
a: 'Osmium tetroxide',
b: 'Disulfur decafluoride',
c: 'Tungsten hexafluoride ',
d: 'carbon monoxide'
},
correctAnswer: 'd'
},
{
question: 'What natural disasters could be caused as a consequence of a destructive forest fire?',
answers: {
a: 'Erosion, flash flooding and landslides',
b: 'Tornadoes',
c: 'Snow',
d: 'Tsunami and earthquakes'
},
correctAnswer: 'a'
},
{
question: 'What major factor determines a forest fire’s behaviour?',
answers: {
a: 'Amount of water vapour in air',
b: 'Density of Forests',
c: 'Wind',
d: 'Hours of sunlight'
},
correctAnswer: 'c'
}
];
function start(){
var i;
var j;
var k;
for(i=0; i<ourQuestions.length; i++){
document.getElementById("questions").innerHTML +='<form id="question">Q'+(i+1)+': '+ ourQuestions[i].question;
for(j=0; j<ourQuestions[i].answers.length; j++){
document.forms[i].innerHTML += '</div><div class="answer"><input name="q1" value="'+ ourQuestions[i].answers[j] +'" id="value4" type="checkbox" />' + ourQuestions[i].answers[j] + '<br/>';
}
document.getElementById("questions").innerHTML +='</form><br/><br/>';
}
document.getElementById("questions").innerHTML += '<button onclick="solveQuiz()">Solve Quiz</button>';
}
function solveSurvey(){
var x;
var txt = ' ';
var i = 0;
var correct = 0;
for(i = 0; i < document.forms.length;i++) {
x = document.forms[i];
for(j = 0; j<x.length; j++){
if(x[j].checked) {
correctAnswer = ourQuestions[i].correctAnswer;
if(x[j].value == ourQuestions[i].answers[correctAnswer]){
correct += 1;
}
}
}
}
document.getElementById("questions").innerHTML += 'Correct answers: '+ correct;
}
document.forms[i].innerHTML += '</div><div class="answer"><input name="q1" value="'+ ourQuestions[i].answers[j] +'" id="value4" type="radio" />' + ourQuestions[i].answers[j] + '<br/>';
<div class="surveysection">
<button onclick="start()" id="startSurvey">Start Survey</button>
<div id="questions"></div>
</div>
Here is a fiddle fixing your issue:
https://jsfiddle.net/bradberkobien/x4hjy8m2/3/
Change your function to be startSurvey() instead of just start().
Also, move your document.forms[i].innerHTML += line up into the for loop in your solveSurvey() function.
Also, make sure your script is linked correctly (this was ultimately the problem in repl.it)

How Object inside Objects generate random item?

i have a object inside objects that want to generate randomly, is a questions quiz. i have tried var
index = Math.floor(Math.random() *currentQuestion.answers[letter]);
no luck with it, can anyone help and explain why i cant generate the item randomly ?
i need to generate random answers item inside my createQuiz function, now is fixed exp: A: MJ, B:Pippen, C:Magic and if refresh it will randomly generate A:Pippen B:Magic C:MJ and so on.
my objects variable
const myQuestions = [
{
question: "What's my name ?",
answers: {
item1: "Chris",
item2: "Leborn",
item3: "Webber"
},
correctAnswer: "Chris",
button: "Next"
},
{
question: "What's my age ?",
answers: {
item1: "31",
item2: "30",
item3: "29"
},
correctAnswer: "31",
button: "Next"
},
{
question: "What's my favor NBA star ?",
answers: {
item1: "MJ",
item2: "Pippen",
item3: "Magic"
},
correctAnswer: "MJ",
button: "Done"
}
]
functions
function createQuiz() {
//clear the contents of questions div first
document.getElementById('questionsBox').innerHTML = "";
//clear answers box
document.getElementById('answersBox').innerHTML = "";
//set answer sting
answersCaptcha = [];
//output
output = [];
// for each question...
myQuestions.forEach(
(currentQuestion, questionNumber) => {
// we'll want to store the list of answer choices
const answers = [];
const option = ["A","B","C"];
let count = -1;
for(letter in currentQuestion.answers){
count++;
var index = Math.floor(Math.random() * currentQuestion.answers[letter]);
// i need to generate random answers item here, now is fixed
// exp: A: MJ, B:Pippen, C:Magic and if refresh it will randomly generate A:Pippen B:Magic C:MJ and so on.
answers.push(
`<label>
<input type="radio" name="question${questionNumber}" value="${letter}">
${option[count]} :
${currentQuestion.answers[letter]}
</label>`
);
}
// add this question and its answers to the output
output.push(
`<div class="question"> ${currentQuestion.question} </div>
<div class="answers"> ${answers.join('')} </div>`
);
})
document.getElementById('answersBox').innerHTML = output.join('');
console.log(answersCaptcha);
}
if i understand your question correctly... all you need is shuffle(currentQuestion.answers)
The problem is that letter is not a number - it cannot be used to randomize that way. Here's a solution:
const myQuestions = [{
question: "What's my name ?",
answers: {
item1: "Chris",
item2: "Leborn",
item3: "Webber"
},
correctAnswer: "Chris",
button: "Next"
},
{
question: "What's my age ?",
answers: {
item1: "31",
item2: "30",
item3: "29"
},
correctAnswer: "31",
button: "Next"
},
{
question: "What's my favor NBA star ?",
answers: {
item1: "MJ",
item2: "Pippen",
item3: "Magic"
},
correctAnswer: "MJ",
button: "Done"
}
]
createQuiz()
function createQuiz() {
//clear the contents of questions div first
document.getElementById('questionsBox').innerHTML = "";
//clear answers box
document.getElementById('answersBox').innerHTML = "";
//set answer sting
answersCaptcha = [];
//output
output = [];
// for each question...
myQuestions.forEach(
(currentQuestion, questionNumber) => {
// we'll want to store the list of answer choices
const option = ["A", "B", "C"];
let count = -1;
const answers = shuffleArray(Object.entries(currentQuestion.answers)).map((e, i) => {
return `<label>
<input type="radio" name="question${questionNumber}" value="${e[0]}">
${option[i]} :
${currentQuestion.answers[e[0]]}
</label>`
})
// add this question and its answers to the output
output.push(
`<div class="question"> ${currentQuestion.question} </div>
<div class="answers"> ${answers.join('')} </div>`
);
})
document.getElementById('answersBox').innerHTML = output.join('');
console.log(answersCaptcha);
}
function shuffleArray(arr) {
let array = arr
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
return array
}
<div id="questionsBox"></div>
<div id="answersBox"></div>

(JS) How to get values from this

How can i get the a, b and c from answers and display them in < ul > like this. A: Hyper Text Markup LanguageB: Hyper Text Mark LanguageC: Hyper Text Main Language
If is possible to do it with for loop then please tell me how.
var questions = [
{
question: "Co znamená zkratka HTML?",
answers: {
a: "Hyper Text Markup Language",
b: "Hyper Text Mark Language",
c: "Hyper Text Main Language"
},
correctAnswer: "a"
},
{
question: "Co znamená zkratka www?",
answers: {
a: "Internetový prohlížeč",
b: "Dokumenty",
c: "Celosvětová informační pavučina"
},
correctAnswer: "c"
},
{
question: "Co znamená zkratka FTP?",
answers: {
a: "Protokol pro připojení k internetu",
b: "Program pro čtení pošty",
c: "Souborový transportní protokol"
},
correctAnswer: "c"
},
{
question: "Pro poštovní klienty na internetu se používá",
answers: {
a: "TCP protokol",
b: "IP protokol",
c: "POP3 protokol"
},
correctAnswer: "c"
},
{
question: "Co je ICQ?",
answers: {
a: "Program pro řízení přístupu k Internetu",
b: "Program pro posílání krátkých textových zpráv přes Internet",
c: "Program testující IQ"
},
correctAnswer: "b"
}
];
Just use map
questions.map( s => s.answers[ s.correctAnswer ] );
Edit
I want to show only the answers not correctAnswer
questions.map( s => s.answers );
Try this:
var options = ['a','b','c'];
questions.forEach((question) => {
var liElement = document.createElement('li');
options.forEach((option) => {
var ul = document.createElement('ul');
ul.innerHtml = question.answers[option];
liElement.appendChild(ul);
})
document.body.appendChild(liElement);
});

Categories

Resources