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

293
Vistas
How to get the clicked button id to be used repeatedly later in different functions?

I want to store what is being clicked on, so that it can be used for multiple times in a game of rock-paper-scissors. I need to use this until player or computer scores 5. Any suggestions will be appreciated!

HTML file:

<div class = buttons>
       <button id="rock">Rock</button>
       <button id="paper">Paper</button>
       <button id="scissors">Scissors</button>
   </div>

JavaScript file:

I am able to log the button.id however it's not useful as I'm unable to use it in any other functions.

const buttons = document.querySelectorAll('button');
buttons.forEach(button => button.addEventListener('click', () => {
console.log(button.id)})); //get the button.id

# Update 1

I tried to store it in an array as pointed out in the answers,
const buttons = document.querySelectorAll('button');
buttons.forEach(button => button.addEventListener('click', () => {
      const {id} = button
      playerChoices.push(id)
      handleChoice(id)
    })
);

const handleChoice = id => {
    console.log(id)
    console.log(playerChoices)
  }

I want to use it in this function :game() but I am unable to call the id value, I also tried playerSelection = playerChoices[playerChoices.length - 1]; to take the last element of the array but it errors to "undefined" every time in this function.

function game(){

let playerScore  = 0;
let computerScore  = 0;
    // playRound()
    // until player or computer scores 5
    while (playerScore < 5 && computerScore < 5) {
        const playerSelection = **UNDEFINED**;  
        const computerSelection = counterPlay();
        let roundResult = playRound(playerSelection, computerSelection);

        console.log(playRound(playerSelection, computerSelection));
        console.log("You chose: ", playerSelection, "Computer chose: " ,computerSelection);
        //incrementing the score:
        if(roundResult.search('You win') > -1){
            playerScore++;
        } else if (roundResult.search('You loose') > -1){
            computerScore++;
        }
        console.log("you : ",playerScore , "computer : " , computerScore);
        
        if(computerScore == 5){
            console.log("You lost :( I won");
        }
        else if(playerScore == 5){
            console.log("I lost, you're too good. Congrats on the win!")
        }       
    }
}

How do I store the id to playerSelection every time I click ?

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

You can just store it in an array or pass it to a function

like this

let playerWins = 0
let computerWins = 0
const choices = ['Rock', 'Paper', 'Scissors']
const buttons = document.querySelectorAll('button');
buttons.forEach(button => button.addEventListener('click', () => {
  const {
    id
  } = button
  playMatch(id, Math.floor(Math.random() * choices.length))
}));

const startGame = () => {
  let playerWins = 0
  let computerWins = 0

}

const playMatch = (playerChoice, computerChoice) => {
  const result = (choices.length + playerChoice - computerChoice) % choices.length
  let message
  switch (result) {
    case 0:
      message = `it's a draw`
      break;
    case 1:
      message = `You won ${choices[playerChoice]} beats ${choices[computerChoice]}`
      playerWins++;
      break;
    default:
      message = `You lose ${choices[computerChoice]} beats ${choices[playerChoice]}`
      computerWins++;
  }
    console.log(message)
  if (Math.max(playerWins, computerWins) === 5) {
    alert('game ended')
  }
}
<div id="buttons">
  <button id="0">Rock</button>
  <button id="1">Paper</button>
  <button id="2">Scissors</button>
</div>
<div id="scores"></div>

about 4 years ago · Juan Pablo Isaza Denunciar

0

var turns = [];
const buttons = document.querySelectorAll('button');
buttons.forEach(button => button.addEventListener('click', (event)=>{
   console.log(event.target.id);
   console.log(button.id);
   turns.push(button.id);
   console.log(turns);
}));

you are missing one ) of foreach loop and the button.id will then work always use browser console to check for syntax or script errors.

about 4 years ago · Juan Pablo Isaza 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