pblang9 pblang9 - 1 year ago 84
HTML Question

How do I make a list print random numbers with the same sentence 5 times?

I need to print a line 5 times like this.....

I just burped 5 times.
I just burped 5 times.
I just burped 5 times.
I just burped 5 times.
I just burped 5 times.


However I need to make sure the numbers are different in each line. For example:

I just burped 5 times.
I just burped 7 times.
I just burped 1 times.
I just burped 9 times.
I just burped 6 times.


the code that I have right now looks like this

<h3 style="position: absolute;left:118px;top: 88px;"
onClick="myFunction()"><button onclick = "myFunction()"> Click Me </button></h3>


<div id="same"></div>



<script>

function myFunction() {
var x = Math.floor((Math.random() * 10) + 1);
var text= " ";
var i;
for(i=0; i<5; i++){
text += "The number of times I just burped is " + x +"<br><br>";
}
document.getElementById("same").innerHTML = text ;
}

</script>



</body>


Can anyone help with this?

H77 H77
Answer Source

Move the random number generator inside the for loop.

e.g.

function myFunction() {
  let text = " ";
  for (let i = 0; i < 5; i++) {
    let x = Math.floor((Math.random() * 10) + 1);
    text += "The number of times I just burped is " + x + "<br><br>";
  }
  document.getElementById("same").innerHTML = text;
}
<h3 style="position: absolute;left:118px;top: 88px;" onClick="myFunction()"><button onclick="myFunction()"> Click Me </button></h3>

<div id="same"></div>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download