user2942256
user2942256

Reputation: 25

When I append a text element to a DOM element, other text inputs lose their value

I'm trying to set up a form whereby when someone enters a value in a text input, another text input is appended to the form. Here's sample code.

It works, but the text inputs do not retain the values you enter.

<html>
<head>
<title>Addabox</title>
<script type="text/javascript">
var Boxcount=0;
var BaseName = 'roomno';
function AddBox() {
    Boxcount +=1;
    var Fname = BaseName.concat(Boxcount);
    document.getElementById('roomrow').innerHTML += "<input type='text' name="+Fname+" value='' length=4 onchange='AddBox'>";
    }
</script>
</head>
<body>
<h2>Add a room</hr><br>
<table>
<tr><td id='roomrow'><input type='text' name='roomno0' value='' length=4 onchange='AddBox()'></td></tr>
</table>
</body>
</html>

What am I doing wrong?

Upvotes: 0

Views: 43

Answers (2)

Nivas
Nivas

Reputation: 18344

innerHTML copies only the HTML attributes but not properties (that are defined by the DOM). The value attribute holds the initial value of the element and any changes are held by the value property.

So, if your HTML had an initial value, that would also have been copied. See http://jsfiddle.net/nivas/ucu33/ where the text field has a initial value of 0.

You can use DOM manipulation (see cookie monster's answer) or JQuery for this.

Upvotes: 0

cookie monster
cookie monster

Reputation: 10972

If you're going to us HTML, don't do .innerHTML += .... There are several issues with it, one of which you've discovered here.

Use .insertAdjacentHTML() instead.

document.getElementById('roomrow').insertAdjacentHTML("beforeend", "<input type='text' name="+Fname+" value='' length=4 onchange='AddBox()'>");

Though I'd prefer DOM creation/manipulation methods.

var inp = document.getElementById('roomrow').appendChild(document.createElement("input"));
inp.type='text';
inp.name=Fname; 
inp.value='';
inp.length=4;
inp.onchange=AddBox;

Upvotes: 3

Related Questions