Adding HTML elements dynamically to a page

So when I was sitting idle, moosa asked me how to add dynamic textboxes into a form without loosing values of the form values on the previous textboxes.

So I thought of documenting the method here just in case anyone of you might want this.

So we have a form with a text box as shown below :


The goal is to add a form as shown below, Clicking the Add More link will add more input boxes to the html form dynamically.

Add More

The Code to add dynamic Input Elements

The following is the simple javascript code that adds html input elements dynamically to the form. Add to the head tag within <script> tag:

var c = 0; function addfield() { var e = document.createElement("div"); e.innerHTML = '<label for="this_'+c+'">Value '+c+'</label> : '+ '<input type="text" size="30" name="this_'+c+'">'; document.getElementById("extendable").appendChild(e); c++; } The code dynamically creates a
tag with the innerHTML, the html of an
tag. Finally add the following html form to the page. <form id="extendable"> <div> <label for="this_1">Value 1</label> : <input type="text" size="30" name="this_1"> </div> </form> <a href="javascript:addfield();">Add More</a>

The above can be tweaked to add any html tag dynamically to a web page.

11 Nov, 2009
Comments (0)
You may also like
On Facebook
Email Newsletter