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

I attempted to implement a CSS and Typescript animation for a sliding effect, but unfortunately, it isn't functioning

So I'm encountering an issue with this unique ts code: {/* Mobile Menu */} <div className="lg:hidden"> <button className="flex items-center w-8" onClick={toggleMenu}> {isMobileMenuOpen ? ( ...

Is it possible to determine which child element is currently in view within a scrollable parent div?

In an attempt to replicate a "current page" feature using divs, similar to a PDF reader. document.addEventListener("DOMContentLoaded", function(event) { var container = document.getElementById("container"); container.onscroll = function() { let ...

Struggling with mapping through a multidimensional array?

I'm facing an issue with using .map() on a nested array. I initially tried to iterate through my stored data using .map(), and then attempted another iteration within the first one to handle the nested array, but it didn't work as expected. The ...

Enter a socket.IO chat room upon accessing an Express route

Encountering difficulty when attempting to connect to a socket.IO room while accessing a specific route in my Express application. The current setup is as follows: app.js var express = require('express'); var app = express(); var http = requir ...

Omit any items from an array that do not have any child elements

Upon receiving data from the server in the format of a flat tree, I proceed to transfer this data to the JsTree library for tree building. Before sending the data to JsTree, I filter out any empty elements of type "folder" that do not have children. Below ...

Tips for implementing owl carousel in Nuxt.REACT_UNITS_CODIFY

Is there a way to make the script function on every page without the need for these pages to be reloaded? I have the Owl Carousel script in my static folder, and I have already included it in nuxt.config.js as shown below: head: { title: 'title&ap ...

Invalid Data Pusher for User Information in Next JS

Hello everyone, I've been practicing using Pusher with Next.js but encountered an issue where it's showing Error: Invalid user data: 'presence-channel' and I can't seem to solve it no matter how hard I try. Could someone please he ...

Trick for adjusting padding on top and bottom for responsive blocks of varying widths

Hello there, I've been working on a project where I need to create a responsive grid of cards, like news articles, that maintain their proportions even when the browser's width changes. To achieve this, I decided to use an aspect-ratio hack by s ...

Troubleshooting issues with ASP.NET bundling and minification when using Angular.js

After reviewing many questions on the same topic, none of them were able to solve my specific case. Our current challenge involves bundling and minifying AngularJs files within .Net code. The following code snippet shows how we are bundling our files insi ...

Selection of multiple listings

Looking for a solution to create a multi list selection area? You can double click on an item in the left list to add it to the selected area. Also, you can double click on an item in the selected area to remove it from the list. <ul id="selection"> ...

A guide on encrypting the data of a file that is uploaded in Meteor.js

As a newcomer to Meteor and coding in general, I have completed tutorial projects and examples and now feel ready to start my own project. I want users to be able to select a file from their computer using an input field, read the contents of the file, and ...

Protractor Throws Element Visibility Issue

When attempting to check a checkbox in the UI, I encounter an "ElementNotVisibleError: element not visible" error. Strangely, I am able to successfully capture and click the checkbox using the console in Chrome developer tools. Has anyone else experience ...

Cloning a checkbox using Jquery

I am working on a search page that utilizes checkboxes to display results. After the user selects certain options and triggers a reload of the page, I want to provide an easy way for them to remove their selections by displaying them at the top of the page ...

A customizable and adaptable Tetris-inspired CSS design perfect for any screen size

If we imagine having a block like this: <div class="block"></div> There are different sizes of the block: <div class="block b1x1"></div> <div class="block b2x1"></div> <div class="block b1x2"></div> For i ...

What is the best way to include a file attachment using a relative path in Nodemailer?

I am currently utilizing the html-pdf converter plugin to transform an HTML page into a PDF file. After conversion, this plugin automatically saves the PDF to the downloads folder. When I attempt to attach a PDF to a nodemailer email, my code looks someth ...

Ways to determine if the keys of an object are present in an array, filtered by the array key

Working on an Angular 2 Ionic application and I'm wondering if there's a straightforward way to filter individuals by age in a specific array and then verify if any key in another object matches the name of a person in the array, returning a bool ...

Retrieving text content within a span element using CSS

Here is the Jsfiddle that I experimented with http://jsfiddle.net/LpH8B/2/ <span>*</span> <br> <span>*</span> <br> <span>hdhdf</span> span[text='*'] { color:red; } I am looking to target ...

Include a fresh attribute in the Interface

How can I include a boolean property isPhotoSelected: boolean = false; in an API interface that I cannot modify? The current interface looks like this: export interface LibraryItem { id: string; photoURL: string; thumbnailURL: string; fi ...

The HTML grid is causing an irritating excess space on the right side of my website

After brainstorming an idea, I decided to create this website for testing purposes. However, the grid layout seems to be causing an unwanted margin on the right side of the page that is not associated with any HTML tag, disrupting the zoom functionality. ...

The jQuery hide and show functions lack precision and are too indiscriminate, requiring a more targeted approach

I am designing a unique contact card that captures a user's name and description from an <input> field and appends the input information into a <div> element. This is the flow I am aiming for... User inputs their first and last name alo ...