Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

154
Views
get value from the button element that I click

I have three button in html:

<button value="Rock" onclick="displayResult()">Rock</button>
<button value="Paper" onclick="displayResult()">Paper</button>
<button value="Scissors" onclick="displayResult()">Scissors</button>

In displayResult() function (wrriten once for 3), how can I get value from the button that I click? If I set ids for all 3 button, I have to write 3 display function to get value from a seperate button:

let displayResultForRock = () => {
  let value = document.getElementById('rock').value;
}
about 4 years ago · Santiago Trujillo
3 answers
Answer question

0

Just attach event listeners to the buttons, and then log the textContent of each.

const buttons = document.querySelectorAll('button');

buttons.forEach(button => {
  button.addEventListener('click', handleClick, false);
});

function handleClick() {
  console.log(this.textContent);
}
<button>Rock</button>
<button>Paper</button>
<button>Scissors</button>

Or use event delegation:

const buttons = document.querySelector('#buttons');

buttons.addEventListener('click', handleClick, false);

function handleClick(e) {
  if (e.target.matches('button')) {
    console.log(e.target.textContent);
  }
}
<div id="buttons">
  <button>Rock</button>
  <button>Paper</button>
  <button>Scissors</button>
</div>

about 4 years ago · Santiago Trujillo Report

0

Please use this code. you can update your displayResult function like this.

function displayResult(event) {
  console.log(event.target.value)
}
<button value="Rock" onclick="displayResult(event)">Rock</button>
<button value="Paper" onclick="displayResult(event)">Paper</button>
<button value="Scissors" onclick="displayResult(event)">Scissors</button>

about 4 years ago · Santiago Trujillo Report

0

const btns = document.querySelectorAll("button")
btns.forEach(b => b.onclick = e => result.innerText = e.target.value)
<button value="Rock">Rock</button>
<button value="Paper">Paper</button>
<button value="Scissors">Scissors</button>
<div id="result"></div>

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!