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?
If you want to dynamically add elements, you should have a container where to place them. For instance, a <div id="container"> . Create new elements by means of document. createElement() , and use appendChild() to append each of them to the container.
Approach 1: Use document. createElement() to create the new elements and use setAttribute() method to set the attributes of elements. Append these elements to the <form> element by appendChild() method. Finally append the <form> element to the <body> element of the document.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With