Dynamically add button, textbox, input, radio elements in html form using JavaScript.

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.

add element form html dynamically javascript

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">&nbsp;</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.



103 Comments

  • Nasir 15 May, 2011, 17:06

    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

  • kiash 27 May, 2011, 7:41

    Useful tutorial.
    Thanks!

  • Ajmal 2 June, 2011, 8:58

    Hai Viral,
    How can i create a struts2 tag dynamically?
    could you help me

  • swathi 2 June, 2011, 15:12

    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…

  • Kuzey Güney 17 June, 2011, 22:43

    i have the same problem issue page type,what to do know for getting
    adsense.

  • Yalan Dünya 17 July, 2011, 19:00

    thanks good post… u blog very nice… i share post…

  • sunny khabrani 25 July, 2011, 10:22

    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.

  • abhishek 3 August, 2011, 0:18

    thanx got dis in frst hit ur blog is gona b hit!

  • Adını Feriha Koydum 10 August, 2011, 17:06

    Hai Viral,
    How can i create a struts2 tag dynamically?
    could you help me

  • Kuzey Güney 10 August, 2011, 17:07

    Useful tutorial.
    Thanks!

  • Jennifer Junio 31 August, 2011, 12:15

    Can i ask a favor?
    btw this tutorial is great :) just what i was looking for.
    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!

  • cire 16 September, 2011, 5:01

    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.

  • yayın akışı 19 September, 2011, 14:14

    Thanks for the code :)

  • Mehmood 29 September, 2011, 21:43

    thanksssss

  • Rakesh 21 October, 2011, 19:27

    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

  • haber 16 December, 2011, 19:32

    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

  • ali 18 December, 2011, 13:29

    so handy and great

  • Shairyar 21 December, 2011, 20:19

    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?

  • Gnanavel 2 January, 2012, 16:52

    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

  • abid 7 January, 2012, 21:23

    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……..

  • harry 15 January, 2012, 23:09

    How can i create a struts2 tag dynamically?
    could you help me

    • Viral Patel 16 January, 2012, 12:04

      @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.

  • Porady 18 January, 2012, 16:29

    How to insert element after input?

  • Nichole 8 February, 2012, 0:06

    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%

  • Piyush 11 February, 2012, 14:24

    how to retrive data inserted in that text box

  • Prasad 21 February, 2012, 12:27

    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

  • Sathish 27 February, 2012, 13:12

    Hai everybody..

    how to validate the dynamically created text box using java script or jquery..

    if u know pls help…

  • Suskunlar 2 March, 2012, 12:39

    @Harry – Sturts2 tag cannot be created here as this is client side code. The rows are dynamically created in Javascript and added to

  • sheetald 6 March, 2012, 15:33

    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…!!!

  • Arvind 20 March, 2012, 10:31

    hi
    nice post i learn a lot..

  • Sumant 7 April, 2012, 18:58

    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??

  • Rahul 25 April, 2012, 12:14

    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

  • mukesh 28 May, 2012, 16:27

    on select create input field .its not working on please help

  • Jennifer 4 June, 2012, 15:55

    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!

    • Viral Patel 4 June, 2012, 16:02

      This is exactly what I am doing in above example. Just call a method add() onclick of Add button. Inside this method use var element = document.createElement("input"); to create new element.

  • haber 11 June, 2012, 18:21

    good practice

  • Satyam 28 June, 2012, 17:31

    After creating text boxes dynamically how can we get that data using either servlet,jsp,struts.

    Please help me.
    advance thanks.

  • Larry 29 June, 2012, 5:00

    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

    • Viral Patel 29 June, 2012, 9:48

      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 :)

  • ray 7 July, 2012, 2:48

    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.

  • Rajveer 8 August, 2012, 0:00

    thanks buddy..it is very helpful for me..really appreciated work.

  • Jalil Khan 8 August, 2012, 11:10

    great …help me much :)

  • vanlongdao 10 August, 2012, 12:10

    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)

  • jeyakiruthika 16 August, 2012, 10:45

    Hi nice post.. I have been searching for this for past three years. Nice .. Thank you very much…

  • Rajat Kapoor 30 August, 2012, 11:29

    HI,

    Nice post this is really helpful article.

  • anjani 6 September, 2012, 16:17

    helpful for freshers in js..

  • PRIYANK RASTOGI 11 November, 2012, 22:15

    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….

  • Raza 15 November, 2012, 16:25

    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?

  • ramakanth 7 January, 2013, 16:06

    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

  • Chris 19 January, 2013, 15:52

    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 :)

  • Chris 19 January, 2013, 18:55

    and can i save the elements that i added for example as a default form?

  • RvMahesan 10 March, 2013, 0:36

    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

  • Nikita 16 March, 2013, 22:08

    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????

Leave a Reply

Your email address will not be published. Required fields are marked *

Note

To post source code in comment, use [code language] [/code] tag, for example:

  • [code java] Java source code here [/code]
  • [code html] HTML here [/code]