Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

303
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!