My divs are multiplying twice as fast with every iteration of the Javascript For Loop

Recently, I developed a script that generates a series of fields based on a number provided by the user (k).

Initially, I had a script that would create the correct number of fields. However, I decided to arrange them like vectors on the screen, so I made adjustments to my script.

I wanted the modified script to generate the appropriate number of fields and place them within DIVS for flexible layout options on the webpage.

However, after making these changes, the script started creating duplicate DIVS as if it goes through the loop twice, but I am unable to determine the cause...

function createFields(k)
{
  k=k+1

  for (var n=1; n<k; n++) {

      var makeBox=document.createElement("div");
      makeBox.id = "box" + n;
      document.getElementById("top").appendChild(makeBox);
      document.getElementById("box" + n).setAttribute('class',"box");

      // More code here...

    }
}

Looking for any suggestions or insights!

UPDATE:

The script is invoked by another function:

function getVectors()
{
  v = document.getElementById("vectorN").value;
  v=parseInt(v); //convert text to an integer
  document.getElementById("q1").innerHTML="Enter your Vectors below!";
  createFields(v);
  document.getElementById("enter").innerHTML="<input type=\"button\" id=\"button\" value=\"Submit Numbers\" onclick=\"canvas()\"/>";

}

This function is triggered by the onChange event in the HTML:

<p id="q1">How many Vectors will you need?
        <input id="vectorN" name="vectorN" type="text" onChange="getVectors()" size="4" maxlength="4">
      </p>

Further UPDATE

Upon examining the console.log, it seems that the createFields() method is only called within the getVectors() function. Strangely enough, it appears to call createFields twice even though it's implemented just once in the script. The sole location where getVectors() is invoked is the onChange event in the input field. Could it be possible that altering the innerHTML and removing the input field triggers another onChange event, thereby causing the function to run again?

Answer №1

Your code implementation appears to be correct. Did you happen to accidentally call the function twice? To verify, insert a console.log statement right after function createFields(k) { and see if it is being executed more than once. It's also worth checking for multiple event listeners on the input field where the user inputs the value of k (such as onkeyup and change).

If unsure about the origin of the createFields function call, search all files for occurrences of createFields. Prior to calling the function, include a

console.log('Calling createFields from here');
to pinpoint where it gets invoked.

Answer №2

Check out this insightful Stack Overflow post that explains the issue. It seems like tabbing out of a text box triggers the onChange event only once, while pressing enter causes it to fire twice, leading to the problem you experienced.

To address this issue, one approach is to monitor the number of fields entered and only generate fields if there's a change in the count.

var fields = 0;

function createFields(k) {
    if (k != fields) {
        fields = k;
        console.log("Fields: " + k);

        //Keep the rest of the code unchanged;
    }
}

See a demonstration here: http://jsfiddle.net/Ej8Ly/5/

You could also implement a similar concept within the getVectors() function.

Answer №3

Instead of dynamically generating all the elements using the DOM, consider constructing a string and then updating the container object's .innerHTML property with that string value. This approach ensures that calling the function multiple times will simply result in overwriting itself and generating consistent output.

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

Script to Trigger Download Button

I'm having trouble with a rar file download on my website (ravens-hangar.tk). A bunch of lines of script keep popping up. Can anyone help me out? Thanks in advance! .download { width: 120px; height: 30px; font-size: 20px; text-align: center ...

"By setting the HTML input box to read-only, the JavaScript button has the

Check out this js fiddle demonstration: http://jsfiddle.net/YD6PL/110/ Here is the HTML code snippet: <input type="text" value="a" readonly> <input type="text"> <input type="text"> <div> <button class="buttons">c</button ...

In Chrome, the height of 100% is not functioning properly within the <div> element

I've been struggling with a problem that I've searched the internet for solutions to, but haven't been able to resolve. The issue revolves around an iframe containing a page that loads specific CSS rules. html, body { position: relative; he ...

Executing a message in Azure Service Bus using Javascript/Node.js

I am utilizing the @azure/service-bus library in a Node.js application to receive messages. The code I am using is as follows: const { ServiceBusClient } = require("@azure/service-bus"); const sbClient = new ServiceBusClient(connectionString); ...

What causes the _.sum() function in lodash to not work with objects in Vuejs?

I've encountered an issue where using Vuejs and Lodash in conjunction with a computed property that calculates the sum of a property in a collection results in unexpected behavior. Instead of summing the values, it seems to concatenate the string [obj ...

Changing the text during a reset process

I've been grappling with this issue, but it seems to slip through my fingers every time. I can't quite put my finger on what's missing. My project involves clicking an image to trigger a translate effect and display a text description. The ...

How can I make the outer function in AJAX's onreadystatechange function return 'true'?

Within my Javascript/AJAX function below, I am striving for a return of true or false: function submitValidate() { var xmlhttp; xmlhttp = null; if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari try { xmlhttp ...

Is there a way to design a table that is responsive and automatically converts to a list when viewed on a mobile device

I am trying to design a responsive table showcasing artists' names. The goal is to have it look similar to this example: After finding and customizing code for the table, I encountered an issue when the table collapses on mobile view. The invisible e ...

Replicating form fields using jQuery

I have come across many questions similar to mine, but unfortunately none of them address the specific details I am looking for. On a single page, I have multiple forms all structured in the same way: <form> <div class="form-group"> ...

Creating a Vue component using v-for and a factory function allows for dynamic

I am currently developing a Table component using factory functions for all logic implementation. Within a v-for loop, I generate a cell for each item in every row. The factory Below are the actual factories that I import into the respective vue page whe ...

Understanding the timing of records being returned via an Observable in Angular's ngOnInit

In my Angular 2 application, I am using an observable to keep track of an array of records. As the results of this observable are stored in the variable "records", I am utilizing *ngFor="let record of records" to iterate over and display them in my view. ...

Looking for assistance with an Angular2 post request?

I'm having an issue with a post request to obtain a token granting access to another access token. Each time I attempt to make the post request, I encounter an error stating that the access_token property is trying to read something undefined. It seem ...

Troubleshooting Socket.IO Communication: Client's emits not reaching server

I have implemented a real-time notification service in a web app using Express and Socket.IO. The client can successfully connect to the server and receive emits from it. However, I am facing an issue where the server is not receiving emits from the client ...

Mobile Iframe in Full View

Currently, I am working on a small project using Angular and Twitter Bootstrap. However, I have encountered a problem. I am trying to create a template that displays content in full screen upon clicking a button. The issue is that the iframe I am using wor ...

Distinguish a specific div within a group of divs by styling it uniquely using just CSS and HTML

I need assistance in selecting the first div with both "con" and "car" classes among all the divs using a CSS selector. <div class="box"> <div class="con">1</div> <div class="con be">2</div> <div class="con car">3& ...

Implement a Loop that Generates Buttons with Popups Using jQuery Mobile

Within the context of XML parsing, I have utilized this code to generate buttons dynamically using a loop: $('#button' + counter + paramcounter).click(function(){ sendData(escape(parameterarray[cnt2] + $('#textinput' + cnt + cnt2).v ...

The setInterval function in JavaScript fails to update the result

I have successfully implemented a countdown function that is working as expected. // Set the date we're counting down to var countDownDate = new Date("<?= $stop_datejs ?>"); // Update the count down every 1 second var x ...

How to style a div's height responsively behind a circle using CSS

Can a CSS pattern be created with responsive design, ensuring that the background line is always in the correct position and height regardless of window size? https://i.sstatic.net/27Tf2.jpg ...

Is it possible to alter the video dynamically according to the state in Vuex?

I am working on a small web application that mimics the appearance of FaceTime. My goal is to switch between video elements by clicking a "Next" button, which will update a value in Vuex and swap out the video accordingly. I initially attempted this appr ...

Is there a restriction on the number of routes available from Google Maps Directions Service?

Utilizing the Google Maps Directions API, I am able to calculate the distance between the current user's location and various stores. Everything functions properly until I exceed 10 store locations, at which point the API ceases to operate due to its ...