Reputation: 130
I'm trying to get this to work where when a user types in a number and it creates the corresponding number of input fields. I've tried with onclick and onchange and nothing seems to happen. Any idea what I'm missing?
var siblings = document.getElementById('siblings');
var value = siblings.value;
siblings.onchange = function(){
let i = 0;
do{
var newField = document.createElement('input');
newField.setAttribute('type','text');
newField.setAttribute('name','siblingInfo[]');
newField.setAttribute('class','siblingInfo');
newField.setAttribute('siz',50);
siblings.appendChild(newField);
i++
}
while (i < value);
}
<i>Do you have any siblings? </i>
<input type="number" id="siblings" name="siblings" min="0">
Upvotes: 0
Views: 531
Reputation: 13506
There are two points in your code needs to change:
let value = siblings.value;
should be inside the onchange
functionsiblings.appendChild(newField);
can change to siblings.appendChild(newField);
since siblings
is input
type and can not append childvar siblings = document.getElementById('siblings');
siblings.onchange = function(){
let value = siblings.value;
let i = 0;
do{
var newField = document.createElement('input');
newField.setAttribute('type','text');
newField.setAttribute('name','siblingInfo[]');
newField.setAttribute('class','siblingInfo');
newField.setAttribute('siz',50);
// to make each element in one line we can add a br element before the newField
siblings.parentNode.appendChild(document.createElement('br'));
siblings.parentNode.appendChild(newField);
i++
}
while (i < value);
}
<div>
<i>Do you have any siblings? </i>
<input type="number" id="siblings" name="siblings" min="0">
</div>
Upvotes: 1