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
CodePudding user response:
You can just store it in an array or pass it to a function
like this
const playerChoices = []
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)
}
<div class=b uttons>
<button id="rock">Rock</button>
<button id="paper">Paper</button>
<button id="scissors">Scissors</button>
</div>
CodePudding user response:
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.