Reputation: 195
I would like my button to display questions in my list of objects in order and based on their status (only show questions with status 0). If the question is showed, the status will change to 1 and in the next round it will not be showed again. I would like to keep on going until all the objects in my list have a status of 1.
I have managed to get a semi-working version. The only problem is that it doesn't skip the objects with status 1, it just doesn't display them when I click the button. I would like the "click" to skip everything until it finds a status of 0 and then display that. Hope that makes sense.
Current code:
var button = document.querySelector("button")
var textDisplay = document.querySelector("div")
var index = 0;
var questions = [{
letter: "a",
answer: ["aaaa"],
status: 0,
question: ["question 1"]
},
{
letter: "b",
answer: ["bbbb"],
status: 0,
question: ["question 2"]
},
{
letter: "c",
answer: ["cccc"],
status: 0,
question: ["question 3"]
},
{
letter: "d",
answer: ["dddd"],
status: 1,
question: ["question 4"]
},
{
letter: "e",
answer: ["eeee"],
status: 0,
question: ["question 5"]
},
{
letter: "f",
answer: ["ffff"],
status: 1,
question: ["question 6"]
}
]
function nextQuestion() {
if (questions[index].status === 0) {
textDisplay.innerHTML = questions[index].question[1];
questions[index].status = 1
index = index + 1;
index = index % questions.length;
} else {
index = index + 1;
index = index % questions.length;
}
}
button.addEventListener("click", function() {
nextQuestion();
})
<button type="button">Whatup</button>
<div>
text
</div>
Upvotes: 2
Views: 53
Reputation: 663
You need a loop to iterate through all the questions to check which is the next one to show. Something like this:
var button = document.querySelector("button");
var skip = document.getElementById("skip");
var textDisplay = document.querySelector("div")
var index = -1;
var questions = [
{ letter: "a", answer: ["aaaa"], status: 0, question: ["question 1"]
},
{ letter: "b", answer: ["bbbb"], status: 0, question: ["question 2"]
},
{ letter: "c", answer: ["cccc"],status: 0, question: ["question 3"] },
{ letter: "d", answer: ["dddd"], status: 1, question: ["question 4"]
},
{ letter: "e", answer: ["eeee"], status: 0, question: ["question 5"]
},
{ letter: "f", answer: ["ffff"], status: 1, question: ["question 6"] }
]
function nextQuestion() {
for(var i = 0; i < 6; i++) {
if (questions[i].status===0) {
textDisplay.innerHTML = questions[i].question;
questions[i].status=1
index = i;
break;
}
}
}
function skipQuestion() {
for(var i = 0; i < 6; i++) {
index++;
if (index > 5) {
index = 0;
}
if (questions[index].status===0) {
textDisplay.innerHTML = questions[index].question;
break;
}
}
}
button.addEventListener("click", function() {
nextQuestion();
});
skip.addEventListener("click", function() {
skipQuestion();
});
<button type="button">Whatup</button>
<button id = "skip">Skip</button>
<div>
text
</div>
Upvotes: 1