Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 932
Mohammad Usman Avatar asked Apr 13 '11 22:04

Mohammad Usman


People also ask

How do you add inputs dynamically?

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.

How do I create a dynamic form in HTML?

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.


2 Answers

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 
like image 69
Zach Avatar answered Sep 26 '22 06:09

Zach


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); 
like image 25
Alex Jolig Avatar answered Sep 26 '22 06:09

Alex Jolig