Basically, I'm using HTML and JavaScript to make a simple rock, paper, scissors game where a button activates a randomly generated string from an array (rock, paper, or scissors). I already have it so that the button randomly generates a computer choice and it displays my choice (using radio buttons) in a box below. I'm stuck because I don't know how to display the randomly generated computer choice again in another box.
I tried using if else statements but I can't figure out how to reference the randomly chosen string from the array. Here is what I tried before within the html game:
<script>
function myFunction();{
if (document.getElementById("randomSelect")) = 'rock'{
document.getElementById('computerChoice').innerHTML = 'rock'
} if (document.getElementById("randomSelect")) = 'paper'{
document.getElementById('computerChoice').innerHTML = 'paper'
} if (document.getElementById("randomSelect")) = 'scissors'{
document.getElementById('computerChoice').innerHTML = 'scissors'
}
}
</script>
<p id = "computerChoice"></p>
Also, sorry if this makes no sense. I'm new to coding.
Generate random number between 0 and 2 (Array Index). Store items in an array and pull out based on random Index generated.
var items = ["rock", "paper", "scissors"]; document.getElementById("randomSelect").addEventListener('click', myFunction); function myFunction() { /*Generate random number between 0 and 2*/ var randomNum = Math.floor(Math.random() * 3); /*Set the random Item*/ document.getElementById('computerChoice').innerHTML = items[randomNum]; }
<p id="computerChoice"></p> <button type="button" id="randomSelect">Random</button>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.