How to create <input type=“text”/> dynamically
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?
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
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);
To create number of input fields given by the user
-
Get the number of text fields from the user and assign it to a variable.
var no = document.getElementById("idname").value
-
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");
-
Then assign necessary attributes to the variable.
textfield.type = "text";
textfield.value = "";
-
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);
-
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>
Maybe the method document.createElement();
is what you're looking for.
See this answer for a non JQuery solution. Just helped me out!
Adding input elements dynamically to form