I'm trying to make a simple application where there is 1 global event listener listening for click events.
At the moment whenever I click on a button it returns undefined even though there is text in it (the buttons start off with no text but then gets filled in).
How would you be able to get the value of the button?
let currentQuestion = -1;
let questions = [
{
question: "Question 1",
options: {
option1: "1",
option2: "2",
option3: "3"
},
correct: "1"
},
{
question:"Question 2",
options: {
option1: "4",
option2: "5",
option3: "6"
},
correct: "5"
}
];
document.addEventListener("click", (event)=> {
console.log(event.currentTarget.value);
currentQuestion++;
console.log(currentQuestion);
document.querySelector("#opt1").innerHTML = questions[currentQuestion].options.option1;
document.querySelector("#opt2").innerHTML = questions[currentQuestion].options.option2;document.querySelector("#opt3").innerHTML = questions[currentQuestion].options.option3;
});
<button id="opt1"></button>
<button id="opt2"></button>
<button id="opt3"></button>
<button id="next">Next</button>
According to the mozilla docs: https://developer.mozilla.org/en-US/docs/Web/API/Event/currentTarget
The currentTarget read-only property of the Event interface identifies the current target for the event, as the event traverses the DOM. It always refers to the element to which the event handler has been attached, as opposed to Event.target, which identifies the element on which the event occurred and which may be its descendant.
your event handler is attached to document... which doesnt have a value.
try switching to event.target
console.log(event.target.value);
even then.. buttons dont have value... so you need to look at their innerText instead
console.log(event.target.innerText);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With