<script>
//references the submit button, runs if it is clicked
const sub = document.getElementById("sub");
sub.addEventListener("click", (e) => {
e.preventDefault();
//references every input number
var in1 = document.getElementById("in1").value;
var in2 = document.getElementById("in2").value;
var in3 = document.getElementById("in3").value;
var in4 = document.getElementById("in4").value;
var in5 = document.getElementById("in5").value;
//creates an array and puts all of the inputted values into it
const inputs = new Array();
inputs.push(in1, in2, in3, in4, in5);
//references all of the circles
var num1 = document.getElementById("num1");
var num2 = document.getElementById("num2");
var num3 = document.getElementById("num3");
var num4 = document.getElementById("num4");
var num5 = document.getElementById("num5");
//creates an array and stores all of the references to the circles in it
var circles = new Array();
circles.push(num1, num2, num3, num4, num5);
//creates an array for the generated numbers
var generated = new Array();
for(i = 0; i < 6; i++){
//fills the array with 5 random numbers
let gen = Math.round(Math.random() * 38);
generated.push(gen);
//changes the numbers in the circles to the random numbers
circles[i].innerHTML = generated[i];
}
alert("test");//this doesn't pop up
});
All of my code up to this point works perfectly, and the numbers are correctly added to the circles, but then anything I write after the for loop does not run, and I cannot figure out why. If the alert is anywhere else in the code above the for loop, it pops up with no issues.
Any help is greatly appreciated.
I tried to make an alert pop up to check if anything was running after the for loop, and it did not pop up.
2
Answers
It looks like you are missing a declaration for the
i
variable used in thefor
loop. In JavaScript, it is best practice to declare variables using thelet
orconst
keywords to avoid polluting the global scope.Try updating your for loop declaration to include let before
i
, like this:It could also be an error within the loop such as an infinite loop or an unhandled exception, which may cause the code after the loop to not execute
SME gave you the answer here, the alert never triggers as your code runs and then errors when the loop hits the bad index. Without seeing your HTML I put together this quick demo. It works in Chrome.