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