<HTML>
<HEAD>
<TITLE>Dynamically add controls in html Form using JavaScript</TITLE>
<SCRIPT language="javascript">
var arrinput = new Array(0);
var arrinputValue = new Array(0);
//Begin add elements:
function add(type) {
//var counter = 0;
//Create an input type dynamically.
//var i;
//for(i = 0; i < 1; i++)
//{
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);
//if(i > 3 )
//alert('U cant add anymore controls');
//}
//foo.removeChild(element);
}// End add function
//Begin function delete
function delete(type)
{
var i;
if(document == element)
{
var x;
x = document.getElementById("fooBar");
if (x.innerHTML){ x.innerHTML = '';}
x.parentNode.removeChild(x);
//var d = document.getElementById("fooBar");
//var olddiv = document.getElementById("foobar");
//d.removeChild(type);
}
}
// end function delete
</SCRIPT>
</HEAD>
<BODY>
<script type="text/javascript" src="formbuilder/javascript/manageControl.js"></script>
<FORM>
<H2>Here u can add controls</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>
<OPTION value ="label">Label</OPTION>
<OPTION value ="checkbox">Checkbox</OPTION>
<OPTION value ="dropdownlist">DropDownList</OPTION>
</SELECT>
<INPUT type="button" value="Add" onclick="add(document.forms[0].element.value)"/>
<INPUT type="button" value ="Delete" onclick="delete(document.forms[0].element.value)"/>
<span id="fooBar"> </span>
</FORM>
</BODY>
</HTML>
At first, i propose to distinguish to part : the form to build and the tools to carry out this task.
Secondly you have to distinguish the different elements to build (now only input with different types - label or dropdownlist are not types but others elements which will be probably after...).
Thirdly, it could be useful to give this elements a name. A prompt could allow the user to enter this name....
Besides, when you create a new element, you can store the new object (it type, name...) in an array and full a second dropdownlist describing the existing elements - see changing select element content on the fly). Then it would be possible to select the element to remove...
Bookmarks