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">
CodePudding user response:
There are two points in your code needs to change:
let value = siblings.value;
should be inside theonchange
functionsiblings.appendChild(newField);
can change tosiblings.appendChild(newField);
sincesiblings
isinput
type and can not append child
var 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>