0

I'm building a Rock, Paper, Scissors game using JavaScript and HTML. I made the game work in the console, and now I'm just adding a UI to it. I'm having an issue setting the playerChoice variable using HTML buttons (I was using a prompt before, but that's not very user-friendly).

What I've tried doing is making a function that is supposed to set playerChoice to whatever button is clicked. I set the onClick method for my buttons to run this function, and use the button's value as an input parameter. However, I'm getting "input not defined errors" when I test this.

let playerChoice = ""
function setPlayerChoice(choice){
    playerChoice = choice;
}
<button class="button" id="btnRock" onClick=setPlayerChoice("rock")>Rock</button>
<button class="button" id="btnPaper" onClick=setPlayerChoice("rock")>Paper</button>
<button class="button" id="btnScissors" onClick=setPlayerChoice("scissors")>Scissors</button>
vcable
  • 509
  • 1
  • 5
  • 17

2 Answers2

1

Try this.

let playerChoice = ""

function setPlayerChoice(choice) {
  playerChoice = choice;
  console.log(playerChoice);
}
<button class="button" id="btnRock" onClick="setPlayerChoice('rock')">Rock</button>
<button class="button" id="btnPaper" onClick="setPlayerChoice('paper')">Paper</button>
<button class="button" id="btnScissors" onClick="setPlayerChoice('scissors')">Scissors</button>
Nidhin Joseph
  • 9,981
  • 4
  • 26
  • 48
0

HTML

<button class="button" id="btnRock" onClick=setPlayerChoice("rock")>Rock</button>
<button class="button" id="btnRock" onClick=setPlayerChoice("paper")>Paper</button>
<button class="button" id="btnRock" onClick=setPlayerChoice("scissors")>Scissors </button>

Javascript

var playerChoice = "";
function setPlayerChoice(choice) {
  playerChoice = choice;
}
Thiago Valente
  • 673
  • 8
  • 25