Reputation: 19
I have such code, where click on a button randomly generates some statement. It seems to work for first click, but other just don'do nothing. What is wrong with this code:
<p id="text"></p>
<button onclick="showAdvice()">Click</button>
<script>
var advices = ["statement", "another", "other", "third"];
var choose = Math.floor(Math.random() * advices.length);
function showAdvice(){
document.getElementById("text").innerHTML = advices[choose];
}
</script>
Upvotes: 0
Views: 848
Reputation: 582
You need to declare function this way:
function showAdvice(){
var choose = Math.floor(Math.random() * advices.length);
document.getElementById("text").innerHTML = advices[choose];
}
In your case "choose" defined only once and every call of showAdvice() will return same text.
Upvotes: 2