Bill Bllson
Bill Bllson

Reputation: 179

Adding code to div clears input val

I have a JS function that adds divs of the class PizzaBox to an empty div called PizzaBoxHolder. Why is it that whenever a new line is created, the user-inputted values in the inputs are replaced with the placeholders? Also, as a side note, should I even be using a place holder for a color input?

function newBox
{
    numOfBoxes += 1; //This is a global variable declared elsewhere, other functions use it but only this one modifies it
    var pizzaBoxCode = "<div class = 'PizzaBox'>"
                     + "    <h6>Box number " + numOfBoxes + "</h6>"
                     + "    <p>Color: <input type = 'color' class = 'boxColor' placeholder = '#000000'/></p>"
                     + "    <p>Toppings: <input type = 'text' class = 'toppings' placeholder = 'Anything but anchovies or mushroom! Never anchovies or mushroom!'/></p>"
                     + "</div>";
    var PizzaBoxHolder = document.getElementById("PizzaBoxHolder") //Empty div until this function fills it up
    PizzaBoxHolder.innerHTML += pizzaBoxCode;
}

Any help is appreciated. Thanks!

Upvotes: 0

Views: 37

Answers (1)

lhan
lhan

Reputation: 4635

The way you're currently doing it, is resetting the entire innerHTML of your main PizzaBoxHolder element. By resetting the HTML, you're losing the current values. If you change the code to create an element, and then call .appendChild, it'll work as expected. The reason is, you're only appending a node to the current element.

var pizza = document.createElement("div");
pizza.className += "PizzaBox";
pizza.innerHTML = "<h6>Box number " + numOfBoxes + "</h6><p>Color: <input type='color' class='boxColor' placeholder = '#000000'/></p><p>Toppings: <input type='text' class='toppings' placeholder='Anything but anchovies or mushroom! Never anchovies or mushroom!'/></p>";

var PizzaBoxHolder = document.getElementById("PizzaBoxHolder"); 
PizzaBoxHolder.appendChild(pizza);

Working fiddle.

Upvotes: 1

Related Questions