Adding HTML elements dynamically to a page

2009
11
Nov

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

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 div tag with the innerHTML, the html of an input 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.

Similar Posts
Related Searches




Comments

Post new comment

The content of this field is kept private and will not be shown publicly.