What possible reasons could be causing the code to not run after my for loop?


<script>
    
    //grab all the input values when submit button is clicked
    const sub = document.getElementById("sub");
    sub.addEventListener("click", (e) => {
    e.preventDefault();
    
    //get input values
    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;
    
    //create an array for input values
    const inputs = new Array();
    inputs.push(in1, in2, in3, in4, in5);

    //grab circle elements
    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");
    
    //store circle elements in an array
    var circles = new Array();
    circles.push(num1, num2, num3, num4, num5);
    
    //array to store random numbers
    var generated = new Array();
    
    for(i = 0; i < 6; i++){
        //generate random numbers and update circle elements with them
        let gen = Math.round(Math.random() * 38);
        generated.push(gen);
        circles[i].innerHTML = generated[i];
    
    }
    
    alert("test");//this doesn't pop up
    
    });

Everything seems to be working fine until after the for loop. I can't get anything to run after that point and I'm not sure why. If I move the alert above the for loop, it works without any issues.

I even tried adding an alert after the for loop to see if it would run, but it didn't.

Answer №1

The solution provided by SME clarifies that the alert never triggers because your code runs into errors when it encounters the bad index during the loop. Without access to your HTML, I have created a quick demo that successfully functions in Chrome.

<!DOCTYPE html>
<html lang="en">

<body>
    <input type="button" id="sub" value="PUSH ME">
    <input type="text" value="1" id="in1">
    <input type="text" value="1" id="in2">
    <input type="text" value="1" id="in3">
    <input type="text" value="1" id="in4">
    <input type="text" value="1" id="in5">
    <div id="num1"></div>
    <div id="num2"></div>
    <div id="num3"></div>
    <div id="num4"></div>
    <div id="num5"></div>

    <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 (let i = 0; i < circles.length; 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 will pop up now

        });
    </script>
</body>

</html>

Answer №2

Make sure you are properly defining the i variable within your loop structure. To avoid global scope pollution in JavaScript, always use the let or const keywords when declaring variables.

Update your for loop syntax to include let before i, like so:

    for(let i = 0; i < 10; i++){
        // add your code here
    }

Additionally, be cautious of possible mistakes within the loop itself such as infinite loops or uncaught exceptions that could prevent subsequent code from running correctly.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Repeating every other item in a list using ng-repeat in AngularJS

Using AngularJS version 1.5.3 In my view, I have a list of items that I want to display. After every two items, I would like to show a new div below the first one. <div class="col text-center" ng-repeat="event in weekDay.events"> &nbsp;& ...

Iterating through an array of objects and performing reduction based on various key-value pairs

I am faced with a challenge of consolidating a large array of objects into one single array that has a specific structure. Each item, such as a banana, needs to be present in two separate objects for buy orders and sell orders, each with their own distinct ...

What is the most efficient way to add an attribute in jQuery - using the attr() method, passing attributes as a key-value object, or directly?

There are three ways that I am aware of for adding a href attribute with a relative link in jQuery: using (1) .attr(), (2) attributes as key-value pair in an argument, or (3) direct writing (if you know other methods, please share in your response so I can ...

Gain access to PowerBI reports effortlessly without the need to input any credentials

Seeking guidance on calling Power BI reports from an ASP.NET C# web application while passing credentials, specifically without utilizing Azure AD. Access has been granted to certain users in the Power BI Service workspace with view permissions. We aim t ...

What is the best method for setting a session cookie securely while also using CSRF tokens?

In my express application, I am working on setting the session cookie to be secure. Here is the code snippet I have tried so far: app.use(express.cookieParser()); sessionOptions = definitions.REDIS; sessionOptions.ttl = definitions.session.expiration; app ...

Menu selection that changes dynamically based on radio button selection

Currently, I have four radio buttons and my goal is to have a drop-down menu change based on the selected radio button. Should I pre-write all the drop-down options and display them accordingly, or would it be better to use ajax to fetch the values from th ...

Is it possible for a chrome extension to allow only specific third-party cookies and storage to be

My Chrome extension inserts an iframe from foo.com into bar.com, creating a situation where bar.com now includes a foo.com iframe. However, I have observed that this iframe encounters difficulties when attempting to write to localStorage if the user has ...

Tips for updating specific properties of an object within a MongoDB database using arrays

I have encountered a problem with updating only specific properties of an object in my MongoDB database. While the query I'm using is working for most variables, it unexpectedly sets certain arrays (media: [] and sports: []) in the athleteProfile back ...

jQuery cannot access a hidden CSS property

I'm working on a form for my new project and have assigned the same class to all input fields. In my CSS file, I've set the text to be capitalized and it displays correctly. However, when I use jQuery's .val() to get the value of the field, ...

Expanding Vue JS Vuetify Panels in a V-for Loop to Reveal Multiple Panels

When pulling data from a database and looping through it in the DOM using a "v-for" loop, I encountered an issue with Vuetify expansion panel components. The problem is that when a user clicks to open one expansion panel, it ends up opening all other panel ...

Ways to verify if a specific extjs panel has finished loading

After a specific panel has finished loading, I need to insert a JavaScript code (using the panel's ID). What is the best way to ensure that the panel has been fully rendered so that I can access its ID using document.getElementById? Thank you. ...

Do multiple AJAX calls share parameters?

I have a JavaScript function as shown below: function makeAjaxCall(outerParameter1, outerParameter2, outerDivId, paramInput){ $.ajax({ type: "POST", url: "some time taking LargeWebMethod or URL", //may take some time to return output dat ...

Working with JSON in AJAX with Javascript and C# to handle array data

When attempting to send an array via AJAX using JSON, I am encountering a problem where my C# handler is unable to properly handle the query. It seems that the querystrings are merging together inexplicably. In the scenario presented here, I am trying to ...

What is the reason for the checkboxes in vuejs not being rendered with the checked attribute set

When working on an edit form, I encountered a situation where I had multiple options to choose from. These options were fetched via ajax using axios and assigned to the variable permisos in the component. Later, these options are rendered through a v-for l ...

"Learn how to securely redirect to a custom URI scheme with a fail-safe option to display alternative content if not supported

In short: Can a visitor be redirected to a custom URI scheme or shown alternate content if the scheme is not supported? My specific scenario involves developing a mobile app that utilizes a custom URI scheme for users to invite others to actions within th ...

What is the best way to transfer $scope to a service in angular.js?

I have two services listed below. When navigating to a specific URL, I need to resolve "OtherService.promise". However, for certain routes, I would prefer to utilize a scope variable within the AppService method instead of the promise. How can I make thi ...

A comparison between the if statement and switch statement in JavaScript

Let's dive into a challenging scenario for those who consider themselves experts in JavaScript, particularly with switch and if statements. Here is how it typically works: var a = 1; if (a == 1) alert("true"); This is just a basic example. Now, let& ...

substituting the deep watcher in Angular

In my application, I am working with a data object called fulldata, which consists of an array of objects. fulldata = [ {'key': 'abc', values: {.....},....}, {'key': 'efg', values: ...

Adding negative values to the Tailwind CSS utility plugin is a simple process that can greatly enhance

Adding Negative Values to Tailwind CSS Utility Plugin Quick Summary: I've developed a custom Tailwind utility plugin that includes numeric values. I'm looking for a way to introduce negative numbers by adding a - at the start of the class, simi ...

validation using ajax and php

One question I have is, when I include document.getElementById('myPassword').value); in the validarDados function, it corresponds to valor. Then I need another variable, but valor1 isn't working as expected. The result of echoing $valor1; is ...