I think I am missing something in my fundamental understanding of creating dynamic HTML elements with javascript. After trying many of the examples I have found online to similar issues I have decided to post my question. I have a JS function which dynamically creates three input forms but I want to label each of the input boxes.
function newItem(){
instance++;
var oldInput = document.getElementById("itemInfo");
var parent = oldInput.parentNode;
var newDiv = document.createElement("div");
var item = document.createElement("INPUT");
var qty = document.createElement("INPUT");
var color = document.createElement("INPUT");
item.name = "item" + instance;
item.value = "Enter Item";
qty.name = "qty" + instance;
qty.value = "Enter Qty";
color.name = "color" + instance;
color.value = "Enter Color";
newDiv.appendChild(item);
newDiv.appendChild(qty);
newDiv.appendChild(color);
p = qty.parentNode;
var itemLabel = document.createElement("Label");
itemLabel.setAttribute("for", item);
itemLabel.innerHTML = "Item: ";
newDiv.insertBefore(itemLabel, item);
var qtyLabel = document.createElement("Label");
qtyLabel.setAttribute("for", qty);
qtyLabel.innerHTML = "Qty: ");
document.body.appendChild(qtyLabel, qty);
var colorLabel = document.createElement("Label");
colorLabel.setAttribute("for", color);
colorLabel.innerHTML = "Color: ");
color.appendChild(colorLabel);
parent.insertBefore(newDiv, oldInput);
}
If I comment out as follows I am able to correctly only the first input box:
var itemLabel = document.createElement("Label");
itemLabel.setAttribute("for", item);
itemLabel.innerHTML = "Item: ";
newDiv.insertBefore(itemLabel, item);
// var qtyLabel = document.createElement("Label");
// qtyLabel.setAttribute("for", qty);
// qtyLabel.innerHTML = "Qty: ");
// document.body.appendChild(qtyLabel, qty);
// var colorLabel = document.createElement("Label");
// colorLabel.setAttribute("for", color);
// colorLabel.innerHTML = "Color: ");
// color.appendChild(colorLabel);
However, if I uncomment either of the bottom two in an attempt to label the second and third input boxes, clicking the button with the newItem() function action does not create any additional input forms. How can I dynamically create the forms with their respective labels?