My code currently works how it should other than herb2 and herb3 not showing up or using the randomizer. I'm not very experienced with coding and have no idea how to make this work.
<!DOCTYPE html>
<html>
<body>
<br>
<p>- - - - - - - - - - - - - - -</p>
<p>D1X (MOD1)</p>
<p>
EPN419<br>
Tesla 1 (left): <span id="demo1"></span><br>
Tesla 1 (right): <span id="demo2"></span><br>
Tesla 2: <span id="demo3"></span><br>
Tesla 3: <span id="demo4"></span><br>
</p>
<script>
for (var x = 1; x < 4; x ) {
document.getElementById("demo" x).innerHTML =
Math.floor(Math.random() * 8) 2 '0%';
}
</script>
</body>
</html
CodePudding user response:
When your script runs, it finds only one demo id.
Here's code that is using 3 separate IDs.
<!DOCTYPE html>
<html>
<body>
<br>
<p>- - - - - - - - - - - - - - -</p>
<p>Herbs Availability</p>
<p>
Herb1 - <a id="demo"></a>
Herb2 - <a id="demo1"></a>
Herb3 - <a id="demo2"></a>
</p>
<script>
document.getElementById("demo").innerHTML =
Math.floor(Math.random() * 8) 2 '0%';
document.getElementById("demo1").innerHTML =
Math.floor(Math.random() * 8) 2 '0%';
document.getElementById("demo2").innerHTML =
Math.floor(Math.random() * 8) 2 '0%';
</script>
</body>
</html
Your next learning step could be for loops to avoid repetition.
Example using a for loop (adjusted ID to demo1 to demo3), see For Loop in Javascript (document.getElementById)
<!DOCTYPE html>
<html>
<body>
<br>
<p>- - - - - - - - - - - - - - -</p>
<p>Herbs Availability</p>
<p>
Herb1 - <a id="demo1"></a>
Herb2 - <a id="demo2"></a>
Herb3 - <a id="demo3"></a>
</p>
<script>
for (var x = 1; x < 4; x ) {
document.getElementById("demo" x).innerHTML =
Math.floor(Math.random() * 8) 2 '0%';
}
</script>
</body>
</html