johnOby
johnOby

Reputation: 23

Multiple input fields using JS

Got the following JS code:

<script language="javascript">
fields = 0;
pNR = 0;
err = 0;

function addInput() {
    if (fields != 40) {
        document.getElementById('text').innerHTML += "<input type='text' name='first" + pNR + "' value='' /><input type='text' name='second" + pNR + "' value='' /><br />";
        fields += 1;
        pNR += 1;
    } else {
        if (err == 0) {
            document.getElementById('text').innerHTML += "<br />Adaugati maxim 40 ingrediente.";
            err = 1;
        }
        document.form.add.disabled = true;
    }
}
</script>

and the following HTML:

<input name="name" style="color:#ffffff;" class="name required" type="button" onclick="addInput()" value="Add" />   

<div id="text">
</div>

By default, there are no fields. When I press the Add button (fields are added two by two with different names), fill in the fields and click again the Add button, the filled fields are emptied. What did I do wrong?

Upvotes: 1

Views: 8217

Answers (1)

Quentin
Quentin

Reputation: 943166

You aren't simply adding new inputs.

You are:

  • converting the existing ones to HTML (the value attribute is unchanged, it will still have the default value, not the current value)
  • adding the HTML for the new inputs to it
  • generating new DOM elements from that HTML.

Don't use innerHTML. Use createElement, appendChild and friends.


This:

document.getElementById('text').innerHTML += "<input type='text' name='first" + pNR + "' value='' /><input type='text' name='second" + pNR + "' value='' /><br />";

Becomes this:

var firstInput = document.createElement("input");
var secondInput = document.createElement("input");

firstInput.type = secondInput.type = "text";
firstInput.name = "first" + pNR;
secondInput.name = "second" + pNR;

var text = document.getElementById("text");
text.appendChild(firstInput);
text.appendChild(secondInput);
text.appendChild(document.createElement("br"));

And, for the else case:

var text = document.getElementById("text");
text.appendChild(document.createElement("br"))
text.appendChild(document.createTextNode("Adaugati maxim 40 ingrediente."));

Working example: http://jsbin.com/OqIWeMum/2/edit

Upvotes: 2

Related Questions