Dynamically add button, textbox, input, radio elements in html form using JavaScript.
- By Viral Patel on January 21, 2009
Adding Elements like textbox, button, radio button etc in a html form using JavaScript is very simple. JavaScript’s document object has a method called createElement() which can be used to create html elements dynamically.
We had used this function in our tutorial: Dynamic combobox-listbox-drop-down using javascript to add dynamic options to a combo box-listbox. Let us use this function to create textboxes, radio buttons, buttons etc dynamically and add them in our page.

Following is the source code of our example.
<HTML>
<HEAD>
<TITLE>Dynamically add Textbox, Radio, Button in html Form using JavaScript</TITLE>
<SCRIPT language="javascript">
function add(type) {
//Create an input type dynamically.
var element = document.createElement("input");
//Assign different attributes to the element.
element.setAttribute("type", type);
element.setAttribute("value", type);
element.setAttribute("name", type);
var foo = document.getElementById("fooBar");
//Append the element in page (in span).
foo.appendChild(element);
}
</SCRIPT>
</HEAD>
<BODY>
<FORM>
<H2>Dynamically add element in form.</H2>
Select the element and hit Add to add it in form.
<BR/>
<SELECT name="element">
<OPTION value="button">Button</OPTION>
<OPTION value="text">Textbox</OPTION>
<OPTION value="radio">Radio</OPTION>
</SELECT>
<INPUT type="button" value="Add" onclick="add(document.forms[0].element.value)"/>
<span id="fooBar"> </span>
</FORM>
</BODY>
</HTML>
Also note that we have used setAttribute() method to assign the attributes to our dynamically created element.
Demo
Any other way of adding elements dynamically in html page?
Let me know.
If you read this far, you should follow me on twitter here.
Get our Articles via Email. Enter your email address.
hi Viral, i have 3 combo box…
all i want is “how to sum every content in combo box?” while combo box has a Text element, and i want to convert it to integer, so i can use switch command for each combo box….when user switch first combo box then it loads a value, when user switch second combo box, it loads a value
and within form there is a button SUM, when user click SUM it will sum all values from combo boxes and shows into textbox
could u help me…i already done this with php, but i have to do this with Javascript…help me please
Useful tutorial.
Thanks!
Hai Viral,
How can i create a struts2 tag dynamically?
could you help me
Hi im using ajax in my application,after ajax call is executed i wil get new textfields.
now wats my problem is when iam reading the values from new textfields im not getting
wats the problem in this..?
waiting for reply…
i have the same problem issue page type,what to do know for getting
adsense.
thanks good post… u blog very nice… i share post…
Hi Viral,
With the help of above demo i created radio buttons, problem which i m facing is i m not able to select any radio button.
thanx got dis in frst hit ur blog is gona b hit!
Hai Viral,
How can i create a struts2 tag dynamically?
could you help me
Useful tutorial.
Thanks!
Can i ask a favor?
just what i was looking for.
btw this tutorial is great
Anyway, i have a form.. it’s like:
Button <— when clicked it adds a skill field,
FIELD 01
FIELD 02
FIELD 03
Okay it add a field. Now how am i gonna insert the added value fields on mysql tables/database.
can you please do a tutorial since i loved and understand this one
Please please please. gonna wait for your reply.
Thanks!
Doesn’t seem to work anymore in firefox 5 nor IE8 : the name attribute of the inputs is not kept when the input is appended inside the form. Therefor the field cannot be transmitted into the server query.
Thanks for the code
thanksssss
I want to dynamic button for booking the in the airlines ticket.
so how can i create 9*9 button
please give me suggestion becoz i want use in my project
I want to dynamic button for booking the in the airlines ticket.
so how can i create 9*9 button
please give me suggestion becoz i want use in my project
so handy and great
nice example, i am trying to create a form where i need to give access to website admins to be able to create forms easily that means the label name as well, any idea how to do that?
Hi Patel,
This is good to see when the dynamic creation of controls.
“name” property is created for the input element in IE6…. plz can you have solution for that….
thanks,
Gnanavel
nice code, but its not easy to understand , if you explain these element.
(setAttribute
document.createElement(“input”);
foo.appendChild(element);
)
then ist working is easy to understand……..
How can i create a struts2 tag dynamically?
could you help me
@Harry – Sturts2 tag cannot be created here as this is client side code. The rows are dynamically created in Javascript and added to HTML DOM.
How to insert element after input?
I have figured out my function part of my javascript code but am having trouble putting it all together for the output text boxes. this if for a tip calculator. I basically need to be able to put a $ amount in and have it come out as a 15% tip with a total box. I know I am making this way more complicated than it needs to be. If there is anyone that can help I would appreciate it! Thank you!!!
Tip Calculator
function figureTip()
{
var bill = document.forms[1].bill.value;
var tipPercent = document.forms[1].tip_percent.value;
var numPeople = document.forms[1].num_people.value;
var tipAmount = bill * (“.” + tipPercent);
var total = bill * (1 + “.” + tipPercent);
totalPerPerson = total / numPeople;
document.forms[1].tip_amount.value = tipAmount.toFixed(2);
document.forms[1].total.value = total.toFixed(2);
document.forms[1].total_person.value = totalPerPerson.toFixed(2);
}
Tip Calculator
Enter the check amount: $
Tip percentage: 15%
how to retrive data inserted in that text box
Dear Viral,
I would like to add a input text field to a form automatically after entering 2 or 3 characters in the input text field.
Input field 1 (after entering 2 or 3 charcters here it will get the field content from a mysql database and after pressing ENTER it should create additional input text field.
Finally after pressing 2 times ENTER form should get submitted.
I know this is possible but I am no Javascript expert, any help is appreciated.
Thanks
Regards
Prasad
Hai everybody..
how to validate the dynamically created text box using java script or jquery..
if u know pls help…
@Harry – Sturts2 tag cannot be created here as this is client side code. The rows are dynamically created in Javascript and added to
Hey, this really works…Thanks a lot… But tell me, if I want to display the name of the radio button besides the button, how do I do that…
I tried using -> document.getElementByName(‘value’).value(value); also document.write();
Please help me asap…!!!
hi
nice post i learn a lot..
Hey Nice Example Viral. But I have a problem. When I reload the page the added fields are not shown on the web page. Even when the page gets reloaded for validations that time also the extra fields added are lost. Can you please tell me how solve this problem??
hi viral
nice tutorial
My problem is i want to create label with text box which generated by js function
label like menu, first name, last name elc
can you please help me
on select create input field .its not working on please help
Hi Viral, may I know how to create a new textbox / textarea using a button? as in a textbox / textarea will be created once u hit the “add” button. Please reply me as I need help desperately. Thank you!
This is exactly what I am doing in above example. Just call a method
add()onclick of Add button. Inside this method usevar element = document.createElement("input");to create new element.good practice
After creating text boxes dynamically how can we get that data using either servlet,jsp,struts.
Please help me.
advance thanks.
Hi Viral, I use this code in one of my forms like this.
addElement:
function () { var theNewElem = document.createElement('input'); theNewElem.setAttribute('type', 'hidden'); theNewElem.setAttribute('name', 'finaltons'); theNewElem.setAttribute('id', 'finaltons'); theNewElem.setAttribute('value', totaltotal); document.getElementById('formtons').appendChild(theNewElem); }This code adds a hidden input box named ‘finaltons” it also holds the value from another input box called ‘totaltotal”. this is done when the user clicks the update button on the html form. Mu problem is if the user hits the update button multiple times I get multiple ‘finaltons” input boxes created and I don’t that. I want 1, what do I change to prevent a second input box from being added if one already exists? Any help would be appreciated. Thanks
Hi Larry, One way of doing this would be to check if element with id=”finaltons” exists. If it not, then create one. Fox example:
if (! document.getElementById('finaltons')) { // add new element here. }Hope this helps
still no answer on the retrieval questions..
.How can you retrieve (or reset) the text a user enter in the input field?
example:
function F(){
divId = “editorInputFields”;
document.getElementById(divId).innerHTML =”";
T = document.createElement(“input”);
//Assign different attributes to the element.
T.setAttribute(“type”, “text”);
T.setAttribute(“value”, “old text”);
T.setAttribute(“name”, “Tname”);
T.setAttribute(“id”, “Ti”);
var foo = document.getElementById(“formsinhere”);
//Append the element in page (in span).
foo.appendChild(T);
}
function S(){
oFormObject.elements["Tname"].value=”new text”;
}
but its not working.
thanks buddy..it is very helpful for me..really appreciated work.
great …help me much
Hi Viral ! I have a question !
This code create dynamic input tags but the same Attributes , and now , I want to create dynamic input tags with other Attributes then What do I do ?
Ex :
Note : Attributes name with different value (txt_1 , txt_2)
Hi nice post.. I have been searching for this for past three years. Nice .. Thank you very much…
HI,
Nice post this is really helpful article.
helpful for freshers in js..
hi viral,
i m using this code
var element3 = document.createElement(‘input’);
element3.type = ‘submit’;
element3.onSubmit=’return validate1();’;
element3.name = ‘sub’;
foo5.appendChild(element3);
it is working in mozilla fine…….. but in google chrome the dynamically created buttons and other fields also are not shown, please help
Reply as soon as possible….
How can we take value on php page?if we use ajax post method to take values?if we create two txt boxes now i want to retrive value on next page?how can i do?
ok u above code is working perfectly nice… but give me one solution for this….how to post this text field values……how to post this textfield(auto generated dynamically generated) values to database… please help me. please send that solution to my mail id
hi sir viral i just want to ask if how to put labels in the code for example:
(This is a label)[This is a textbox]
and also i would like to know is it possible that the elements can go down one line to arrange the elements you have entered please give me guidelines I am very new to this thanks
and can i save the elements that i added for example as a default form?
function addfil(elem,tagName,idval,html)
{
var p=document.getElementById(elem);
var newElement = document.createElement(tagName);
newElement.setAttribute(‘id’,idval);
newElement.innerHTML=html;
p.appendChild(newElement);
}
var fileId=0;
function addcall()
{
fileId++;
var remove=”;
var html = ”+
”+
”+
”+
‘ ‘+
”+
”+
”+
”+
”+
”+
‘Upload your certificate ‘+fileId+”+
‘:’+
‘Remove‘+
”+
” ;
addfil(‘file’,'p’,fileId,html);
}
function rem_fil(elementId)
{
var element = document.getElementById(elementId);
element.parentNode.removeChild(element);
fileId–;
}
Untitled Document
Add New
if i want to add a button dynamically on an image when the mouse comes over it, how could i do that??? and after the button is shown , by clicking on it, it a menu box should be displayed. How can do this??? Will u give me some suggestions????