Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

event.currentTarget.value returning undefined javascript

Tags:

javascript

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>
like image 562
n212 Avatar asked Sep 12 '25 11:09

n212


1 Answers

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);
like image 142
DynasticSponge Avatar answered Sep 15 '25 00:09

DynasticSponge