Home > database >  Adding new form fields based on a number input
Adding new form fields based on a number input

Time:11-22

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?&nbsp;</i>
   <input type="number" id="siblings" name="siblings" min="0">

CodePudding user response:

There are two points in your code needs to change:

  1. let value = siblings.value; should be inside the onchange function
  2. siblings.appendChild(newField); can change to siblings.appendChild(newField); since siblings is input 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?&nbsp;</i>
   <input type="number" id="siblings" name="siblings" min="0">
</div>

  • Related