Having trouble with the code below. When user clicks a button, I want to set the value of clickedAnswer accordingly. Then I can validate the button clicked against the answer later on. Currently, I'm logging a 4 every time. Any help is greatly appreciated!
let clickedAnswer = 1;
function setClickedAnswer(button) {
if (button.id === "option1") {
clickedAnswer = 1;
} else if (button.id === "option2") {
clickedAnswer = 2;
} else if (button.id === "option3") {
clickedAnswer = 3;
} else {
clickedAnswer = 4;
}
validateAnswer();
console.log(clickedAnswer);
}
answer1.addEventListener("click", setClickedAnswer);
answer2.addEventListener("click", setClickedAnswer);
answer3.addEventListener("click", setClickedAnswer);
answer4.addEventListener("click", setClickedAnswer);
The function is expecting the button itself to be passed:
function setClickedAnswer(button) {
However, no such button is passed:
answer1.addEventListener("click", setClickedAnswer);
What is sent to an event handler by default is the event object itself , which has a target
property referring to the element invoking the event. So you can do this:
if (button.target.id === "option1") {
(repeat for the other conditions, of course)
Alternatively, if you prefer the function to expect a button element, you can wrap a function around your event handler invokation and pass the element there:
answer1.addEventListener("click", () => setClickedAnswer(answer1));
or:
answer1.addEventListener("click", function () { setClickedAnswer(answer1); });
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.