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

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

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 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