I want to create an input type text in my web form dynamically. More specifically, I have a textfield where the user enters the number of desired text fields; I want the tex
The core idea of the solution is:
input
elementtext
This can be done via this simple script:
var input = document.createElement('input');
input.setAttribute('type', 'text');
document.getElementById('parent').appendChild(input);
Now the question is, how to render this process dynamic. As stated in the question, there is another input where the user insert the number of input to generate. This can be done as follows:
function renderInputs(el){
var n = el.value && parseInt(el.value, 10);
if(isNaN(n)){
return;
}
var input;
var parent = document.getElementById("parent");
cleanDiv(parent);
for(var i=0; i
Insert number of input to generate:
Generated inputs:
but usually adding just an input is not really usefull, it would be better to add a name to the input, so that it can be easily sent as a form. This snippet add also a name:
function renderInputs(el){
var n = el.value;
var input, label;
var parent = document.getElementById("parent");
cleanDiv(parent);
el.value.split(',').forEach(function(name){
input = document.createElement('input');
input.setAttribute('type', 'text');
input.setAttribute('name', name);
label = document.createElement('label');
label.setAttribute('for', name);
label.innerText = name;
parent.appendChild(label);
parent.appendChild(input);
parent.appendChild(document.createElement('br'));
});
}
function cleanDiv(div){
div.innerHTML = '';
}
Insert the names, separated by comma, of the inputs to generate:
Generated inputs: