I want to create three buttons and only one of them should be the winner. When I click on the winner button, the output will be "Congratulations. You have found the winner button!" and if the clicked button is not the winning one, the output will be "Keep trying."
The winner button will be the one whose id will match a randomly chosen value between 1 and 3. This value will be generated within the function "WinnerButton(buttonCnt)" with the help of the method "Math.random()".
<p>Which button is the winner ?</p>
<button type = "submit" id = "1" onclick = "handleClick(this.id)"></button>
<button type = "submit" id = "2" onclick = "handleClick(this.id)"></button>
<button type = "submit" id = "3" onclick = "handleClick(this.id)"></button>
<pre id = "output"></pre>
<script>
let buttonCnt = 3;
const output = document.querySelector('#output');
function WinnerButton(buttonCnt) {
let Winner = Math.ceil(Math.random() * buttonCnt);
return Winner;
}
function handleClick(clicked_id) {
if (Number(clicked_id) === WinnerButton(buttonCnt)) {
output.textContent = "Congratulations. You have found the winner button!"
} else {
output.textContent = "Keep trying."
}
}
</script>
The problem is that if I check the winner button in the console and click it, there are certain cases when the clicked button is not the winner. If you click on the image below, you will see that even though the console says that the winner button is number 3, I receive the message "Keep trying" if I click on it. I know that you don't see that I clicked on the third button, but you can trust me that I did it.
I don't understand why is this happening. Can you please explain me? I don't want a straight solution, but an explanation of what I am doing wrong.
Thank you very much.
You should only once use function WinnerButton
because if you use it in handleClick
it every time change the winner id.
let buttonCnt = 3;
let winnerId = WinnerButton(buttonCnt)
const output = document.querySelector('#output');
function WinnerButton(buttonCnt) {
let Winner = Math.ceil(Math.random() * buttonCnt);
return Winner;
}
function handleClick(clicked_id) {
if (Number(clicked_id) === winnerId) {
output.textContent = "Congratulations. You have found the winner button!"
} else {
output.textContent = "Keep trying."
}
}
<p>Which button is the winner ?</p>
<button type = "submit" id = "1" onclick = "handleClick(this.id)">1</button>
<button type = "submit" id = "2" onclick = "handleClick(this.id)">2</button>
<button type = "submit" id = "3" onclick = "handleClick(this.id)">3</button>
<pre id = "output"></pre>