I'm creating a quiz app that pulls data from an API, builds a series of questions, and then loads a different number of "answer elements" on the quiz page each time, depending on which question is randomly selected from the array.
Below is a function to create a series of clickable "player cards" that are a valid answer to the CSS card style. The idea is that the user selects a card and then clicks the check button to run the function to check if it is correct.
The feature works fine except for one thing. Users can select all cards.
The problem I have is that you can click on all the answers and they all get the CSS class and the data is passed to all selected cards/answers.
I just want the user to choose one answer. They can click on any card and change their mind, but they can only select an answer and then proceed through the answer check feature.
I do not know what to do? Can anyone help me understand how I need to change this code to achieve this?
function addClickEvent(answers) { const playerCard = document.querySelectorAll(".player-card"); for (i = 0; i < playerCard.length; i++) { playerCard[i].setAttribute("id", [i]); playerCard[i].addEventListener("click", (e) => { clickedPlayer = e.target; clickedPlayer.classList.add("border-lime-500"); clickedPlayer.classList.add("border-8"); let userAnswer = answers[clickedPlayer.id]; checkButton.addEventListener("click", () => { checkAnswer(userAnswer, answers); }); }); } }
P粉2708916882024-01-30 00:32:27
Store the answer in a variable with a larger scope than the listener. Whenever any answer is submitted, the variable will be overwritten. Then declare a separate checkButton
listener. If the variable holding the answer is not empty, check the answer.
function addClickEvent(answers) { const playerCard = document.querySelectorAll(".player-card"); let userAnswer = null; for (i = 0; i < playerCard.length; i++) { playerCard[i].setAttribute("id", [i]); playerCard[i].addEventListener("click", (e) => { clickedPlayer = e.target; clickedPlayer.classList.add("border-lime-500"); clickedPlayer.classList.add("border-8"); userAnswer = answers[clickedPlayer.id]; }); } checkButton.addEventListener("click", () => { if(!userAnswer) return alert("Select an answer first!"); checkAnswer(userAnswer, answers); }); }
The code above does not make the frontend "deselect" other cards when they are clicked (if you want that too), but it is an easy fix.