• Home
  • Jobs
  • Courses
  • Questions
  • Teachers
  • For business
  • ES/EN

0

29
Views
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 1 month ago ·

Juan Pablo Isaza

2 answers
Answer question

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 1 month ago · Juan Pablo Isaza Report

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 1 month ago · Juan Pablo Isaza Report
Answer question
Find remote jobs
Loading

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post job Plans Our process Sales
Legal
Terms and conditions Privacy policy
© 2022 PeakU Inc. All Rights Reserved.