Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

157
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda