I wrote some code for a multiple choice card template and am having 3 issues.
-
When I set the background color on the back side (green or red depending on if the answer is correct) using document.body.style.backgroundColor = “/” it carries over to the next card.
-
What is the text content of an empty field? I would like to check for this and if so, not draw the field.
-
The input checkboxes do not work on the ankimobile app. They are hidden and nested within labels so that if you click anywhere on the label it checks the checkbox. It works on desktop but on mobile it just brings you to the back of the card instead.
Does anyone know of solutions to any of these issues?
Here is my code:
Front Template
<header>
{{Front}}
</header>
<div id="fcontainer"></div>
<label class="front">
<input type="checkbox" id="A">
{{Choice 1}}
</label>
<label class="front">
<input type="checkbox" id="B">
{{Choice 2}}
</label>
<label class="front">
<input type="checkbox" id="C">
{{Choice 3}}
</label>
<label class="front">
<input type="checkbox" id="D">
{{Choice 4}}
</label>
<script>
document.body.style.backgroundColor = "navy";
var fcontainer = document.querySelector("#fcontainer");
var fchoices = document.querySelectorAll(".front");
var randomSet = new Set();
/* Draw choices in random order */
while(randomSet.size < 4) {
randomSet.add(Math.floor(Math.random()*4));
}
for (var f of randomSet) {
//TO DO: find a way to filter out empty field
fcontainer.appendChild(fchoices[f]);
fchoices[f].hidden = false;
}
</script>
Back Template
<header>
{{Front}}
</header>
<div id="bcontainer"></div>
<div class="back">{{Choice 1}}</div>
<div class="back">{{Choice 2}}</div>
<div class="back">{{Choice 3}}</div>
<div class="back">{{Choice 4}}</div>
<script>
var bcontainer = document.querySelector("#bcontainer");
var bchoices = document.querySelectorAll(".back");
var questionCorrect = true;
var answers = "{{Answer #}}".split(",");
for (var b of randomSet) {
var finput = fchoices[b].querySelector("input");
var checked = finput.checked;
var correct = answers.includes(finput.id);
var bchoice = bchoices[b];
/* Re-draw choices in the same random order */
bcontainer.appendChild(bchoice);
bchoice.hidden = false;
/* Change the border if checked */
if(checked) {
bchoice.style.borderStyle = "inset";
} else {
bchoice.style.borderStyle = "outset";
}
/* Change the color if correct or incorrect */
if(correct) {
bchoice.style.backgroundColor = "#00ff00";
bchoice.style.borderColor = "#00cc00";
} else {
bchoice.style.backgroundColor = "#ff0000";
bchoice.style.borderColor = "#cc0000";
}
/* Set question as incorrect if choice is wrong */
if (!checked===correct) {
questionCorrect = false;
}
}
/* Change the to the appropriate background color if correct or not */
if(questionCorrect){
document.body.style.backgroundColor = "#009900";
} else {
document.body.style.backgroundColor = "#990000";}
</script>