kalhoon kalhoon - 4 years ago 58
Javascript Question

How can I display a new random number on each line with a JavaScript for loop?

How can display a new random number with each new line element?

Currently, my HTML is displaying
The number is 4
The number is 4
The number is 4
The number is 4
The number is 4

I would like it to show a random number with each line.
The number is 4
The number is 1
The number is 9
The number is 3
The number is 11

<!DOCTYPE html>
<html>
<head>
<title></title>

</head>
<body>

<div id="info">

</div>


<script src="main.js"></script>
</body>

</html>

var divInfo = document.getElementById('info');
var quote = document.createElement('p');

var randNum = Math.floor(Math.random() * 11) + 1;
var messNum = '';



for (var i = 0; i < 5; i++) {

messNum = "The number is " + randNum + "</br>";
divInfo.appendChild(quote);
quote.innerHTML += messNum;

}

Answer Source

You are assigning randNum once outside of your for loop.

Put randNum = Math.floor(Math.random() * 11) + 1; as your first line inside the for loop, that way it changes with every iteration

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