chickenwings123
chickenwings123

Reputation: 123

Counter value is not increasing, value remains constant in javascript

why does my variable pc_score and my_score not increase? The output is 0. I have two more functions of the eventListener format that I omitted from the code, but it should not affect the results. . I edited the post for runnable code. Thank you. Thanks for looking at my question.



<script>

    var options = ['rock','paper','scissors']
    let my_score = 0; 
    var pc_score = 0; 

    let computerChoice ;


    function computerSelection() {

         computerChoice = options[Math.floor(Math.random()*options.length)]
         return computerChoice;

    }


    var results = document.getElementById("result")
    document.getElementById("rock").addEventListener("click", ()=> {
        playerChoice=rock;
        computerSelection();
        if (computerChoice=='rock'){
             results.innerHTML="It is a tie";
        } else if (computerChoice=='paper'){
            results.innerHTML="It is a loss";
                 pc_score += 1;
        }else if (computerChoice=='scissors'){
            results.innerHTML="It is a win";
            my_score+= 1
        }

})

     const you = document.getElementById("You")
        you.innerHTML= my_score
    const computer = document.getElementById("Computer")
        computer.innerHTML=pc_score

  </script>

Upvotes: 1

Views: 395

Answers (2)

Mamun
Mamun

Reputation: 68933

Since you are assigning the value outside the event handler function that code does not get executed when click happens (instead those code is executed on page load with the initial value). You have to update the HTML inside the event handler function.

Also I will suggest you to use innerText or textContent if the text is plain text (not htmlString).

Try the following:

var my_score = 0; 
var pc_score = 0;
const you = document.getElementById("You");
const computer = document.getElementById("Computer");
document.getElementById("scissors").addEventListener("click", ()=> {
    playerChoice=scissors;
    computerSelection();
    if (computerChoice == "rock"){
        results.textContent = "It is a loss";
        pc_score++;
    } else if (computerChoice == "paper"){
        results.textContent = "It is a win";
        my_score++;
    }else if (computerChoice=="scissors"){
        results.textContent = "It is a tie";
    }
    you.textContent = my_score;
    computer.textContent = pc_score;
});

Upvotes: 1

glace
glace

Reputation: 2210

You are updating the score variables, but not the innerHTML's of the elements showing that score. There surely is a better/cleaner way to do this, but just call computer.innerHTML=pc_score and you.innerHTML= my_score again after changing the value

Upvotes: 0

Related Questions