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?