I need to create fields dynamically in child table using JavaScript based on a value entered by a user.
eg. if the user enters a 5 then 5 fields has to be created. Is it possible?
I need to create fields dynamically in child table using JavaScript based on a value entered by a user.
eg. if the user enters a 5 then 5 fields has to be created. Is it possible?
Yes it's possible.
Step 1: Read the value of the input field to determine how many new fields to create.
// parseInt is necessary because DOM input values are string types.
const numberOfFields = parseInt(input.value)
Step 2: Dynamically create the new input fields.
for (let i=0; i < numberOfFields; i++) {
const input = document.createElement('input')
document.body.appendChild(input)
}
See the working code below.
I've added comments for explanation.
function addInput() {
//get input value
var inputVal = document.getElementById("inputVal").value;
//container for new inputs
var container = document.getElementById("container");
// if inputVal is greater than 0 append new inputs
for (i = 0; i < inputVal; i++) {
var newInput = document.createElement("input");
container.appendChild(newInput);
}
}
<p>Select number and submit to add more inputs</p>
<input id="inputVal" type="number"></input>
<br/>
<div id="container">
</div>
<br />
<button onclick="addInput();">Add Input</button>