Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

309
Visualizações
When a user clicks a button, how do you store a variable that can be used later?

I'm working on a "Rock, Paper, Scissors" project. The user clicks one of three buttons (either rock, paper, or scissors), then the computer will choose, then the winner is displayed. Once the user selects which one they want to play, I want to be able to use the variable "userChoice" that has their choice later in the code.

This is my HTML for buttons:

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

This is my Javascript:

document.addEventListener('DOMContentLoaded', function(event) {
   document.querySelector('#Rock').onclick=function(e){
     const userChoice = "Rock"; 
   }
   document.querySelector('#Paper').onclick=function(e){
     const userChoice = "Paper"; 
   }
   document.querySelector('#Scissors').onclick=function(e){
     const userChoice = "Scissors"; 
   }})
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Try this approach. Now when the user clicks the Log user choice button you see what they have clicked.

    let
        userChoice = ''

    document.querySelector('#Rock').onclick = function() {
        userChoice = "Rock";
    }
    document.querySelector('#Paper').onclick = function() {
        userChoice = "Paper";
    }
    document.querySelector('#Scissors').onclick = function() {
        userChoice = "Scissors";
    }

    let
        user_choice = document.querySelector('#user-choice')

    user_choice.addEventListener('click', function() {
        console.log(userChoice)
    })
<div class="buttons">
    <button id="Rock">Rock</button>
    <button id="Paper">Paper</button>
    <button id="Scissors">Scissors</button>
</div>

<p>
    <button id="user-choice">Log user choice</button>
</p>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda