Ad

Rock, Paper, Scissors If Statement Not Working

- 1 answer

The code is working until "if statement". I feel the logic is correct, but I guess the syntax is not. I hope the code is clear enough. I have three buttons in HTML for rock, paper and scissors and each button has "onclick" function. For example when the "rock" button is pressed, "rock" shows up in h3 id="yourChoice". There is another h3 id="computerChoice" which two I wanted to compare in if statements, but without intended outcome. Thank you!

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

var computerChoice = document.getElementById("computer_choice");
var yourChoice = document.getElementById("your_choice");

var finalScore = document.getElementById("final_score");


function random(mn, mx){
    return Math.random()*(mx - mn) + mn;
}
function userRock(){
    computerChoice.innerHTML = arr[Math.floor(random(1, 4))-1];
    yourChoice.innerHTML = "rock";
}
function userPaper(){
    computerChoice.innerHTML = arr[Math.floor(random(1, 4))-1];
    yourChoice.innerHTML = "paper";
}
function userScissors(){
    computerChoice.innerHTML = arr[Math.floor(random(1, 4))-1];
    yourChoice.innerHTML = "scissors"
}

//the following part is not working
if(yourChoice.innerHTML == "paper" && computerChoice.innerHTML == "paper"){
    finalScore.innerHTML == "It`s a tie";
}else if(yourChoice.innerHTML == "paper" && computerChoice.innerHTML == "scissors"){
    finalScore.innerHTML = "You lose!";
}else if(yourChoice.innerHTML == "paper" && computerChoice.innerHTML == "rock"){
    finalScore.innerHTML = "You win";
}else if(yourChoice.innerHTML == "rock" && computerChoice.innerHTML == "paper"){
    finalScore.innerHTML = "You lose!";
}else if(yourChoice.innerHTML == "rock" && computerChoice.innerHTML == "rock"){
    finalScore.innerHTML = "It`s a tie";
}else if(yourChoice.innerHTML == "rock" && computerChoice.innerHTML == "scissors"){
    finalScore.innerHTML = "You win!";
}else if(yourChoice.innerHTML == "scissors" && computerChoice.innerHTML == "scissors"){
    finalScore.innerHTML = "It`s a tie";
}else if(yourChoice.innerHTML == "scissors" && computerChoice.innerHTML == "rock"){
    finalScore.innerHTML = "You lose!";
}else if(yourChoice.innerHTML == "scissors" && computerChoice.innerHTML == "paper"){
    finalScore.innerHTML = "You win!";
}else{
finalScore.innerHTML = "End of game!";
}
Ad

Answer

By using var yourScore = document.getElementById("your_score"); you are just getting the element and not the value.

Comparison should be

yourChoice.innerHTML == "paper" && computerChoice.innerHTML == "paper"
Ad
source: stackoverflow.com
Ad