106

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 text fields to be generated dynamically in the same form.

How do I do that?

wxs
  • 288
  • 3
  • 18
Mohammad Usman
  • 1,061
  • 2
  • 7
  • 3

14 Answers14

188

With JavaScript:

var input = document.createElement("input");
input.type = "text";
input.className = "css-class-name"; // set the CSS class
container.appendChild(input); // put it into the DOM
Zach
  • 7,730
  • 3
  • 21
  • 26
  • Im sorry, but im not being able to show it on my form? i have made a function which gets fired when the add button gets clicked. But i cant figure it out how to get vlaue from that text field on which user types fer the number of text fields to create . . ? And what if i also wanted to assign a css class to these dynamically created text fields . . ? – Mohammad Usman Apr 13 '11 at 22:58
  • I added some code to the example to show appending it to the DOM and adding a CSS class to the dynamically created element. – Zach Apr 13 '11 at 23:25
  • 1
    This does not creates `` it creates `` – Sebi2020 Nov 19 '21 at 15:58
36

Using Javascript, all you need is document.createElement and setAttribute.

var input = document.createElement("input");
input.setAttribute('type', 'text');

Then you can use appendChild to append the created element to the desired parent element.

var parent = document.getElementById("parentDiv");
parent.appendChild(input);
Ghasem
  • 14,455
  • 21
  • 138
  • 171
13

To create number of input fields given by the user


  1. Get the number of text fields from the user and assign it to a variable.

    var no = document.getElementById("idname").value


  1. To create input fields, use createElement method and specify element name i.e. "input" as parameter like below and assign it to a variable.

    var textfield = document.createElement("input");


  1. Then assign necessary attributes to the variable.

    textfield.type = "text";

    textfield.value = "";


  1. At last append variable to the form element using appendChild method. so that the input element will be created in the form element itself.

    document.getElementById('form').appendChild(textfield);


  1. Loop the 2,3 and 4 step to create desired number of input elements given by the user inside the form element.

    for(var i=0;i<no;i++) {           
        var textfield = document.createElement("input");
        textfield.type = "text"; textfield.value = "";
        document.getElementById('form').appendChild(textfield);
    }
    

Here's the complete code

function fun() {
    /*Getting the number of text fields*/
    var no = document.getElementById("idname").value;
    /*Generating text fields dynamically in the same form itself*/
    for(var i=0;i<no;i++) {
        var textfield = document.createElement("input");
        textfield.type = "text";
        textfield.value = "";
        document.getElementById('form').appendChild(textfield);
    }
}
<form id="form">
    <input type="type" id="idname" oninput="fun()" value="">
</form>
Ajithraj
  • 528
  • 5
  • 15
4

See this answer for a non JQuery solution. Just helped me out!

Adding input elements dynamically to form

Community
  • 1
  • 1
jaaq
  • 1,188
  • 11
  • 29
  • 2
    Very nice. I don't understand why people are giving examples with jquery all the time. thank you. – kdobrev Apr 07 '17 at 16:23
4

Maybe the method document.createElement(); is what you're looking for.

Eliasdx
  • 2,190
  • 2
  • 23
  • 33
4

You could do something like this in a loop based on the number of text fields they enter.

$('<input/>').attr({type:'text',name:'text'+i}).appendTo('#myform');

But for better performance I'd create all the html first and inject it into the DOM only once.

var count = 20;
var html = [];
while(count--) {
  html.push("<input type='text' name='name", count, "'>");
}
$('#myform').append(html.join(''));

Edit this example uses jQuery to append the html, but you could easily modify it to use innerHTML as well.

SavoryBytes
  • 35,571
  • 4
  • 52
  • 61
  • 8
    Might be good to mention that this depends on jQuery, as the question didn't specify jQuery. – Jeff Apr 13 '11 at 22:38
4

The core idea of the solution is:

  • create a new input element
  • Add the type text
  • append the element to the DOM

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<n; i++){
    input = document.createElement('input');
    input.setAttribute('type', 'text');
    parent.appendChild(input);
  }
}

function cleanDiv(div){
  div.innerHTML = '';
}
Insert number of input to generate: </br>
<input type="text" onchange="renderInputs(this)"/>

<div id="parent">
Generated inputs:
</div>

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: </br>
<input type="text" onchange="renderInputs(this)"/>
<br>
Generated inputs: </br>
<div id="parent">

</div>
Greedo
  • 3,438
  • 1
  • 13
  • 28
2

I think the following link will help you. If you want to generate fields dynamically and also want to remove them on the same time you can get the help from here. I had the same question, So i got the answer

$(function() {
        var scntDiv = $('#p_scents');
        var i = $('#p_scents p').size() + 1;

        $('#addScnt').live('click', function() {
                $('<p><label for="p_scnts"><input type="text" id="p_scnt" size="20" name="p_scnt_' + i +'" value="" placeholder="Input Value" /></label> <a href="#" id="remScnt">Remove</a></p>').appendTo(scntDiv);
                i++;
                return false;
        });

        $('#remScnt').live('click', function() { 
                if( i > 2  ) {
                        $(this).parents('p').remove();
                        i--;
                }
                return false;
        });
});

http://jsfiddle.net/jaredwilli/tZPg4/4/

  • The remove part of this code is rather imperfect. If you add 2 inputs and remove the middle one you end up with 2 inputs with the same ID. Better remove the line with `i--;` Also you're going to have to handle the original and the additional input fields seperately if you put it into a form processed by PHP. – jaaq Feb 08 '17 at 17:17
2

Try this:

function generateInputs(form, input) {
  x = input.value;
  for (y = 0; x > y; y++) {
    var element = document.createElement('input');
    element.type = "text";
    element.placeholder = "New Input";
    form.appendChild(element);
  }
}
input {
  padding: 10px;
  margin: 10px;
}
<div id="input-form">
  <input type="number" placeholder="Desired number of inputs..." onchange="generateInputs(document.getElementById('input-form'), this)" required><br>
</div>

The code above, has a form with an input which accepts a number in it:

<form id="input-form">
  <input type="number" placeholder="Desired number of inputs..." onchange="generateInputs(document.getElementById('input-form'), this)"><br>
</form>

The input runs a function onchange, meaning that when the user has entered a number and clicked submit, it run a function. The user is required to fill out the input with a value before submitting. This value must be numerical. Once submitted the parent form and the input are passed to the function:

...
generateInputs(document.getElementById('input-form'), this)
...

The generate then loops according to the given value inside the input:

...
x = input.value;
for (y=0; x>y; y++) {
...

Then it generates an input inside the form, on each loop:

...
var element = document.createElement('input');
element.type = "text";
element.placeholder = "New Input";
form.appendChild(element);
...

I have also added in a few CSS stylings to make the inputs look nice, and some placeholders as well. To read more about creating elements createElement():

https://www.w3schools.com/jsref/met_document_createelement.asp

To read more about for loops:

https://www.w3schools.com/js/js_loop_for.asp

topsoftwarepro
  • 773
  • 5
  • 19
2
        var input = document.createElement("input");

        input.setAttribute("type", "text");

        input.setAttribute("name", "name");

        input.setAttribute("value", 'value');

        document.getElementById("divID").appendChild(input);
reza_qsr
  • 21
  • 2
1

You could use createElement() method for creating that textbox

Sean
  • 381
  • 1
  • 5
  • 19
1

you can use ES6 back quits

  var inputs = [
        `<input type='checkbox' id='chbox0' onclick='checkboxChecked(this);'> <input  type='text' class='noteinputs0'id='note` + 0 + `' placeholder='task0'><button  id='notebtn0'                     >creat</button>`, `<input type='text' class='noteinputs' id='note` + 1 + `' placeholder='task1'><button  class='notebuttons' id='notebtn1' >creat</button>`, `<input type='text' class='noteinputs' id='note` + 2 + `' placeholder='task2'><button  class='notebuttons' id='notebtn2' >creat</button>`, `<input type='text' class='noteinputs' id='note` + 3 + `' placeholder='task3'><button  class='notebuttons' id='notebtn3' >creat</button>`, `<input type='text' class='noteinputs' id='note` + 4 + `' placeholder='task4'><button  class='notebuttons' id='notebtn4' >creat</button>`, `<input type='text' class='noteinputs' id='note` + 5 + `' placeholder='task5'><button  class='notebuttons' id='notebtn5' >creat</button>`, `<input type='text' class='noteinputs' id='note` + 6 + `' placeholder='task6'><button  class='notebuttons' id='notebtn6' >creat</button>`, `<input type='text' class='noteinputs' id='note` + 7 + `' placeholder='task7'><button  class='notebuttons' id='notebtn7' >creat</button>`, `<input type='text' class='noteinputs' id='note` + 8 + `' placeholder='task8'><button  class='notebuttons' id='notebtn8' >creat</button>`, `<input type='text' class='noteinputs' id='note` + 9 + `' placeholder='task9'><button  class='notebuttons' id='notebtn9' >creat</button>`
    ].sort().join(" ");
   document.querySelector('#hi').innerHTML += `<br>` +inputs;
<div id="hi"></div>
Omar bakhsh
  • 896
  • 11
  • 18
1
<button id="add" onclick="add()">Add Element</button>

<div id="hostI"></div>

<template id="templateInput">
    <input type="text">
</template>

<script>
    function add() {

        // Using Template, element is created
        var templateInput = document.querySelector('#templateInput');
        var clone = document.importNode(templateInput.content, true);

        // The Element is added to document
        var hostI = document.querySelector('#hostI');
        hostI.appendChild(clone);
    }

</script>

HTML Templates are now the recommended standards to generate dynamic content.

Agnel Vishal
  • 564
  • 6
  • 13
  • Worth noting this isn't supported on IE. [MDN docs](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/template) – Cocowalla Jan 14 '21 at 13:25
0
  • Query and get the container DOM element

  • Create new element

  • Put new element to document Tree

//Query some Dib region you Created
let container=document.querySelector("#CalculationInfo .row .t-Form-itemWrapper");
let input = document.createElement("input");

//create new Element  for apex
input.setAttribute("type","text");
input.setAttribute("size","30");
containter.appendChild(input); // put it into the DOM