Question index not updating when I click next button - javascript

I have written this code its just that when I click the next button the questions and answers don't update and go to the next question in the array, but it shows the first question and answers when the page loads. I'm not sure what I havent done here.
const questiontext= document.getElementById('question-text');
const A= document.getElementById('OptionA');
const B= document.getElementById('OptionB');
const C= document.getElementById('OptionC');
const D= document.getElementById('OptionD');
const options= document.getElementsByClassName('options');
const nextbutton= document.getElementById('next');
const submitbutton= document.getElementById('submit');
const questions=[
{
question: "What is the best item at mcdonalds?",
answerA: "Fries",
answerB: "Big Mac",
answerC: "Mcnuggets",
answerD: "Quarter Pounder",
correctanswer: "Big Mac"
},
{
question: "What is the cheapest thing on the mcdonalds menu?",
answerA: "Fries",
answerB: "Double Cheeseburger",
answerC: "Happy Meal",
answerD: "Orange juice",
correctanswer: "Fries"
},
{
question: "What is the least popular item at mcdonalds?",
answerA: "Filet O Fish",
answerB: "Hamburger",
answerC: "Veggie Deluxe",
answerD: "Mineral water",
correctanswer: "Filet O Fish"
},
{
question: "How many dips are you allowed with 20 Mcnuggets?",
answerA: "2",
answerB: "4",
answerC: "3",
answerD: "6",
correctanswer: "4"
}
];
//Question index at start
const questionindex= 0;
const currentquestion= () =>{
questiontext.innerHTML= questions[questionindex].question;
A.innerHTML= questions[questionindex].answerA;
B.innerHTML= questions[questionindex].answerB;
C.innerHTML= questions[questionindex].answerC;
D.innerHTML= questions[questionindex].answerD;
if(questionindex === questions.length){
submitbutton.classList.remove('hidden');
}
}
const nextquestion= () =>{
questionindex++
}
//Load first question and answers
currentquestion(questionindex);
//Button to display next question
nextbutton.addEventListener('click', nextquestion);

change the const and replace it with a let or var

Change
const questionindex
to
let questionindex

Related

replace a key value pair from a GET request without mutating the original JSON

I have a task to return some an object by name of recipe and include a list of it's ingredients and also an object that replaces the instructions with a key value pair of "numSteps": count_of_instruction_steps. I am having a hard time with removing the key of "instructions" for the result.
This is the .json file of recipes:
{
"recipes": [
{
"name": "scrambledEggs",
"ingredients": [
"1 tsp oil",
"2 eggs",
"salt"
],
"instructions": [
"Beat eggs with salt",
"Heat oil in pan",
"Add eggs to pan when hot",
"Gather eggs into curds, remove when cooked",
"Salt to taste and enjoy"
]
},
{
"name": "garlicPasta",
"ingredients": [
"500mL water",
"100g spaghetti",
"25mL olive oil",
"4 cloves garlic",
"Salt"
],
"instructions": [
"Heat garlic in olive oil",
"Boil water in pot",
"Add pasta to boiling water",
"Remove pasta from water and mix with garlic olive oil",
"Salt to taste and enjoy"
]
},
{
"name": "chai",
"ingredients": [
"400mL water",
"100mL milk",
"5g chai masala",
"2 tea bags or 20 g loose tea leaves"
],
"instructions": [
"Heat water until 80 C",
"Add milk, heat until 80 C",
"Add tea leaves/tea bags, chai masala; mix and steep for 3-4 minutes",
"Remove mixture from heat; strain and enjoy"
]
}
]
}
The task is the following:
A GET request to http://localhost:3000/recipes/details/garlicPasta should return, if recipe exists, this .json:
Response body (JSON):
{
"details":
{
"ingredients": [
"500mL water",
"100g spaghetti",
"25mL olive oil",
"4 cloves garlic",
"Salt"
],
"numSteps":5
}
}
Status: 200
And should return this if it does not exist:
Response body (JSON): {}
Status: 200
This is what I am actually getting:
{
name: "garlicPasta",
ingredients: [
"500mL water",
"100g spaghetti",
"25mL olive oil",
"4 cloves garlic",
"Salt"
],
instructions: {
numSteps: 5
}
}
My code is the following:
app.get('/recipes/details/:name', (req, res) => {
let count = 0
const numSteps = {}
const recipe = recipes.find(r => r.name === req.params.name)
const instructions = recipes.map(r => {
if(r.name === req.params.name){
for(let instruction of r.instructions){
count += 1
}
}
})
recipe.instructions = {"numSteps": count}
res.status(200).send(recipe);
})
I wouldn't try to return a modified "recipe" object since the shape of the response you need is different. You can use your existing code to find the correct recipe, and then just create a new object with the response properties you want. Note that you can just use recipe.instructions.length to know how many steps there are.
app.get('/recipes/details/:name', (req, res) => {
let count = 0;
const recipe = recipes.find(r => r.name === req.params.name);
const output = {
details: {
ingredients: recipe.ingredients,
numSteps: recipe.instructions.length
}
};
res.status(200).send(output);
})
You're not creating the details property, and you're adding an instructions property in the result that you don't want.
There's no need to loop to count numSteps, you can just use r.instructions.length. And once you find the recipe with recipes.find(), you don't need another loop to find the recipe name.
You're not checking whether the recipe can be found, so that you return {} in that case.
app.get('/recipes/details/:name', (req, res) => {
const recipe = recipes.find(r => r.name === req.params.name);
let result = {};
if (recipe) {
result.details = {
ingredients: recipe.ingredients,
numSteps: recipe.instructions.length
};
}
res.status(200).send(recipe);
})

How to convert json array to java script using php?

I have this data...
{"quiz":
[{"question":"What is your favorite color?",
"choices":[{"prefix":"A","content":"Red"},{"prefix":"B","content":"Blue"},{"prefix":"C","content":"Yellow"},{"prefix":"D","content":"Pink"}]},
{"question":"What is the equivalent measurement of 1 feet?",
"choices":[{"prefix":"A","content":"12cm"},{"prefix":"B","content":"12px"},{"prefix":"C","content":"12mm"},{"prefix":"D","content":"12inch"}]},
{"question":"What is the combination of Green?",
"choices":[{"prefix":"A","content":"Yellow and Red"},{"prefix":"B","content":"Blue and Orange"},{"prefix":"C","content":"Yellow and Blue"},{"prefix":"D","content":"Black and Skyblue"}]}],"success":1}
and i want to convert it in java script like this one...
const myQuestions = [
{
question: "Who is the strongest?",
answers: {
a: "Superman",
b: "The Terminator",
c: "Waluigi, obviously"
},
correctAnswer: "c"
},
{
question: "What is the best site ever created?",
answers: {
a: "SitePoint",
b: "Simple Steps Code",
c: "Trick question; they're both the best"
},
correctAnswer: "c"
},
{
question: "Where is Waldo really?",
answers: {
a: "Antarctica",
b: "Exploring the Pacific Ocean",
c: "Sitting in a tree",
d: "Minding his own business, so stop asking"
},
correctAnswer: "d"
}
];
how can I achieve this one, because im making a quiz app which will view in mobile device by the use of webviewer. any help is much appreciated..
Here's a start of how you could potentially convert the array. Be aware, there is no correctAnswer column in your input, so it's impossible to convert:
var input = {"quiz":
[{"question":"What is your favorite color?",
"choices":[{"prefix":"A","content":"Red"},{"prefix":"B","content":"Blue"},{"prefix":"C","content":"Yellow"},{"prefix":"D","content":"Pink"}]},
{"question":"What is the equivalent measurement of 1 feet?",
"choices":[{"prefix":"A","content":"12cm"},{"prefix":"B","content":"12px"},{"prefix":"C","content":"12mm"},{"prefix":"D","content":"12inch"}]},
{"question":"What is the combination of Green?",
"choices":[{"prefix":"A","content":"Yellow and Red"},{"prefix":"B","content":"Blue and Orange"},{"prefix":"C","content":"Yellow and Blue"},{"prefix":"D","content":"Black and Skyblue"}]}],"success":1}
console.log(input.quiz.map(({question, choices}) => ({
question,
answers: choices.reduce((obj, v) => Object.assign(obj, {[v.prefix]: v.content}), {}),
correctAnswer: "?",
})));

How can get only key values from the join() values in javascript?

const myQuestions = [
{
level:"Level 1",
questionNo: 1,
sentence: "Her uncles are army officers.",
question: "Q . Which words are about people? ",
answers: {
"1": "a. uncles / officers",
"2": "b. her/are",
"3": "c. in/the"
},
correctAnswer: "1",
topic: "Noun",
description: "plural nouns"
},
{
level:"Level 1",
questionNo: 2,
sentence: "He dropped the glass and it broke into many pieces.",
question: "Q . Which word stands for 'the glass'?",
answers: {
"1": "a. he",
"2": "b. it",
"3": "c. into"
},
correctAnswer: "2",
topic: "Pronoun",
description: "pronoun 'it' and what it has already referred to"
},
....
]
This is my JSON. Here my Html5 codes below
<div class="answers"> ${answers.join("")} </div>
Now we got key and values also like this.
1: a. uncles / officers
But we want only values. Anybody can solve this bug?
You can use Object.values() for this:
${Object.values(answers).join("")}
const myQuestions = [{
level: "Level 1",
questionNo: 1,
sentence: "Her uncles are army officers.",
question: "Q . Which words are about people? ",
answers: {
"1": "a. uncles / officers",
"2": "b. her/are",
"3": "c. in/the"
},
correctAnswer: "1",
topic: "Noun",
description: "plural nouns"
}];
console.log(Object.values(myQuestions[0].answers).join(', '));
When you do:
answers.join("")
then the join method is applied to the entire answers object, and it will concatenate both its keys and values.
In order to feed only the values to join, do:
Object.values(answers).join("")
More specifically:
var answers = myQuestions[0].answers;
console.log(Object.values(answers).join(""));
(as shown in this codepen).
const myQuestions = [{
level: "Level 1",
questionNo: 1,
sentence: "Her uncles are army officers.",
question: "Q . Which words are about people? ",
answers: {
"1": "a. uncles / officers",
"2": "b. her/are",
"3": "c. in/the"
},
correctAnswer: "1",
topic: "Noun",
description: "plural nouns"
}]
const ans = Object.values(myQuestions[0].answers)
console.log(ans)

Load JSON file into JavaScript variable

So, I need to put the following code into a JSON file and load it into a separate JavaScript file:
var allQuestions = [{
question: "What is Elvis Presley's middle name?",
choices: ["David", "Aaron", "Eric", "Jack"],
correctAnswer: 1
}, {
question: "Who is the singer of the Counting Crows?",
choices: ["Adam Duritz", "John Adams", "Eric Johnson", "Jack Black"],
correctAnswer: 0
}, {
question: "Who is the Queen of Soul?",
choices: ["Mariah Carey", "Whitney Houston", "Aretha Franklin", "Beyonce"],
correctAnswer: 2
}, {
question: "Which famous group was once known as The Quarrymen?",
choices: ["The Beatles", "The Birds", "The Who", "Led Zeppelin"],
correctAnswer: 0
}];
In other words, the contents of allQuestions need to go in a JSON file and then loaded into the allQuestions variable in a separate JavaScript file. What would the JSON file look like and how would I load it into the allQuestions variable?
Try using JSON.stringify() , $.getJSON()
What would the JSON file look like
"[
{
"question": "What is Elvis Presley's middle name?",
"choices": [
"David",
"Aaron",
"Eric",
"Jack"
],
"correctAnswer": 1
},
{
"question": "Who is the singer of the Counting Crows?",
"choices": [
"Adam Duritz",
"John Adams",
"Eric Johnson",
"Jack Black"
],
"correctAnswer": 0
},
{
"question": "Who is the Queen of Soul?",
"choices": [
"Mariah Carey",
"Whitney Houston",
"Aretha Franklin",
"Beyonce"
],
"correctAnswer": 2
},
{
"question": "Which famous group was once known as The Quarrymen?",
"choices": [
"The Beatles",
"The Birds",
"The Who",
"Led Zeppelin"
],
"correctAnswer": 0
}
]"
how would I load it into the allQuestions variable?
$.getJSON("/path/to/json", function(data) {
var allQuestions = data;
})
jsfiddle https://jsfiddle.net/dydhgh65/1
You can use the ES6 fetch API, like so:
// return JSON data from any file path (asynchronous)
function getJSON(path) {
return fetch(path).then(response => response.json());
}
// load JSON data; then proceed
getJSON('/path/to/json').then(data => {
// assign allQuestions with data
allQuestions = data;
}
Here is how to do it using async and await.
async function getJSON(path, callback) {
return callback(await fetch(path).then(r => r.json()));
}
getJSON('/path/to/json', data => allQuestions = data);
Try this:
var myList;
$.getJSON('JsonData.json')
.done(function (data) {
myList = data;
});

How do I shuffle an array within an array?

SETUP Description:
I am building a trivia game that has a spinner. This spinner is split up into 6 categories (the 6th category being ALL previous 5 categories combined). The first 5 categories will have it's own set of questions. Once the spinner stops on a category a form appears that will ask a series of questions in order according to it's category. Each question has 3 choices, 1 of them being the correct choice.
Below is a short question bank array to illustrate what I am thinking:
```
var questionBankArray =
[{
category: "Category1",
question: "What does the following expression return? <br> 3 / 'bob';",
choices: ["undefined", "ReferenceError", "NaN"],
correctAnswer: "NaN"
},{
category: "Category1"
question: "What is a method?",
choices: ["Used to describe an object.", "A function assigned to an object.", "Performs a function on one or more operands or variables."],
correctAnswer: "A function assigned to an object."
},{
category: "Category2"
question: "Which company first implemented the JavaScript language?",
choices: ["Netscape Communications Corp.", "Microsoft Corp.", " Sun Microsystems Corp."],
correctAnswer: "Netscape Communications Corp."
},{
category: "Category2"
question: "When was the first release of a browser supporting JavaScript?",
choices: ["1996", "1995", " 1994"],
correctAnswer: "1995"
},
];
```
I would like to go through the questionBanArray of objects, and by category, shuffle within that category. I also want to be able to shuffle the choices within each question of that category. How would I go about this? Would it be harder easier to rewrite it to look like this:
questionBankArray =
[{
CategoryBank1:
[{
question1: "What is blank?",
choices: ["choice1","choice2","answer"],
answer: "answer"
},{
question2: "What is blank?",
choices: ["choice1","choice2","answer"],
answer: "answer"
}],
CategoryBank2:
[{
question1: "What is blank?",
choices: ["choice1","choice2","answer"],
answer: "answer"
},{
question2: "What is blank?",
choices: ["choice1","choice2","answer"],
answer: "answer"
}]
}];
I think the ideal structure would be something like this:
questionBankArray =
[{
category:"first category",
questions:
[{
question1: "What is blank?",
choices: ["choice1","choice2","answer"],
answer: "answer"
},{
question2: "What is blank?",
choices: ["choice1","choice2","answer"],
answer: "answer"
}]
},
{
category: "second category",
questions:
[{
question1: "What is blank?",
choices: ["choice1","choice2","answer"],
answer: "answer"
},{
question2: "What is blank?",
choices: ["choice1","choice2","answer"],
answer: "answer"
}]
}];
Create a shuffle function:
function shuffle(o){
for(var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
return o;
}
Start looping over your outer array and go deeper and deeper, applying the shuffle function from the most inner level to the outer array
for (var category in questionBankArray) {
for (var question in category.questions) {
shuffle(question.choices);
}
shuffle(category);
}
shuffle(questionBankArray);

Categories

Resources