I designed a card template for multiple choice. It works fine for the first card but for following cards it breaks and throws an error “Uncaught SyntaxError: Identifier ‘<variable name>’ has already been declared”
I think this is because it has the variables saved from the previous card which somehow breaks it.
Is there some way to fix this so that the variables are only saved per card or can be overwritten properly?
Here is my code:
Front Template
{{Front}}
<div id="front-choices-container"></div>
<div id="1" class="front-choice">
<label>
<input type="checkbox">
{{Choice 1}}
</label>
</div>
<div id="2" class="front-choice">
<label>
<input type="checkbox">
{{Choice 2}}
</label>
</div>
<div id="3" class="front-choice">
<label>
<input type="checkbox">
{{Choice 3}}
</label>
</div>
<div id="4" class="front-choice">
<label>
<input type="checkbox">
{{Choice 4}}
</label>
</div>
<script>
let frontChoicesContainer = document.querySelector("#front-choices-container");
let frontChoices = document.querySelectorAll(".front-choice");
// Draw choices in random order
const randomSet = new Set();
while(randomSet.size < 4) {
randomSet.add(Math.floor(Math.random()*4));
}
randomSet.forEach((element) => {
frontChoicesContainer.appendChild(frontChoices[element]);
frontChoices[element].hidden = false;
});
</script>
Back Template
{{Front}}
<div id="back-choices-container"></div>
<div id="1" class="back-choice">
<label>
<input type="checkbox">
<span>{{Choice 1}}</span>
</label>
</div>
<div id="2" class="back-choice">
<label>
<input type="checkbox">
{{Choice 2}}
</label>
</div>
<div id="3" class="back-choice">
<label>
<input type="checkbox">
{{Choice 3}}
</label>
</div>
<div id="4" class="back-choice">
<label>
<input type="checkbox">
{{Choice 4}}
</label>
</div>
<p>Correct?</p>
<script>
let backChoices = document.querySelectorAll(".back-choice");
let backChoicesContainer = document.querySelector("#back-choices-container");
let answer = "Correct!";
const answers = "{{Answer #}}".split(",");
// Re-draw choices in the same random order
randomSet.forEach((element) => {
const frontCheckbox = frontChoices[element].querySelector("input");
const backCheckbox = backChoices[element].querySelector("input");
if(frontCheckbox.checked) {
backCheckbox.setAttribute("checked", "");
}
backChoicesContainer.appendChild(backChoices[element]);
backChoices[element].hidden = false;
});
// Color the choices by correctness
backChoices.forEach((choice) => {
const checkbox = choice.querySelector("input");
if(answers.includes(choice.id)) {
choice.style.backgroundColor = "limegreen";
if(!checkbox.checked) {
answer = "Incorrect";
}
} else {
choice.style.backgroundColor = "red";
if(checkbox.checked){
answer = "Incorrect";
}
}
});
// Draw the result
result = document.querySelector("p");
if(answer=="Correct!"){
result.style.color = "limegreen";
} else {
result.style.color = "red";
}
result.textContent = answer;
</script>