0

I'm working on a rock-paper-scissors game in JavaScript. I am having some trouble getting the input of radio buttons from the user. If the bot wins one round it should also add 1 to his score, which it does everytime right now. Here is the code I've tried:

HTML:

<h2 id="score"><span id="pl1">0</span>-<span id="pl2">0</span></h2>
<div id="left">
          <label for="rock">Rock</label><br>
            <input type="radio" name="q" class="q" id="rock"></input><br>
          <label for="paper">Paper</label><br>
            <input type="radio" name="q" class="q" id="paper"></input><br>
          <label for="scissors">Scissors</label><br>
            <input type="radio" name="q" class="q" id="scissors"></input><br>
            <button id="confirm" class="button" onClick="playBot()" style="margin-bottom: 10px;">Confirm</button>
      </div><p id="result"></p>

and the JavaScript:

function playBot(){
 var num = Math.floor((Math.random() * 4) + 1); // generate number between 1 and 3 which represents the item bot has chosen
 console.log(num);
 var rock = document.getElementById("rock").value;
 var paper = document.getElementById("paper").value;
 var scissors = document.getElementById("scissors").value;
 var result = document.getElementById("result");
  // 1 = rock, 2 = paper, 3 = scissors
 if (rock.checked == true && num != 2){
   pl1 = pl1 + 1;
   document.getElementById("pl1").innerHTML = pl1;
 } else if (paper.checked == true && num != 3){
    pl1 = pl1 + 1;
    document.getElementById("pl1").innerHTML = pl1;
} else if (scissors.checked == true && num != 1){
   pl1 = pl1 + 1;
   document.getElementById("pl1").innerHTML = pl1;
} else {
  pl2 = pl2 + 1;
  document.getElementById("pl2").innerHTML = pl2;
}
}

I've tried doing it with the for loop, which wasn't working either. Sources I've tried: How to get value of selected radio button?

Get Radio Button Value with Javascript

http://www.w3schools.com/jsref/prop_radio_checked.asp

Thanks in advance

Community
  • 1
  • 1
Sam B.
  • 5
  • 4

1 Answers1

0

You're fetching strictly the value when assigning to rock, paper, and scissors in these lines:

var rock = document.getElementById("rock").value;
var paper = document.getElementById("paper").value;
var scissors = document.getElementById("scissors").value;

However, your if statements are trying to fetch an attribute by looking at the "checked" attribute. Either fetch the whole element with

var rock = document.getElementById("rock")

and use the "checked" attribute or only check the value with

if (rock)
{
    // Do something
}
Kyte Aryus
  • 161
  • 4
  • woah, thanks for the answer. Didn't know it was this simple, it works great now! Thanks again :) – Sam B. Aug 15 '16 at 15:49
  • Glad I could help! If you click the check mark under the voting buttons on the answer you can list it as "accepted"; That would be much appreciated. – Kyte Aryus Aug 15 '16 at 15:51
  • Yeah I couldn't click it yet, had to wait 3 minutes – Sam B. Aug 15 '16 at 15:52