Reputation: 703
What is wrong with my code? It is supposed to create input tags in html with using the incoming number (quantity):
// Declare variables
var numberOfGrades = 0;
var NL = "\n";
// Functions
function setQuantity() {
numberOfGrades = document.getElementById("quantity").value;
var inputBox = document.createElement("INPUT");
var BR = document.createElement("br"); // Break line
var gradeNumber = 1;
var gradeText = document.createTextNode("Grade " + gradeNumber + ":");
for (var i = 0; i < numberOfGrades; i++) {
alert(numberOfGrades);
document.getElementById("formDiv").appendChild(BR);
document.getElementById("formDiv").appendChild(gradeText);
document.getElementById("formDiv").appendChild(inputBox);
gradeNumber++;
}
}
body {
font-family: "Open Sans", sans-serif;
}
.container {
width: 100%;
background-color: lightcyan;
padding: 10px;
}
<body>
<h1>Homework and Quiz average calculator</h1>
<p>Please Enter the required information to calcuate</p>
<div class="container" id="formDiv">
<form id="formID">
<p>
<strong>Calculate the average of homework grades</strong>
</p>
How many grades?
<input type="number" id="quantity" name="quantity" min="1" max="10" value="1">
<!--<input onclick="setQuantity()" type="submit" value="Apply">-->
</form>
<button onclick="setQuantity()">APPLY</button>
<br>
</div>
<script src="script.js"></script>
</body>
Upvotes: 4
Views: 7217
Reputation: 114481
When you call x.appendChild(y)
the node y
is added as a child from x
removing it from where it was if already in the DOM.
For example:
var x = document.createElement("div");
var y = document.createElement("div");
var z = document.createElement("div");
x.appendChild(y);
z.appendChild(y); // now y is not inside x any more, was **moved** to z
If you want to have multiple nodes you need to create them inside the loop.
Upvotes: 2