You can use JavaScript to add elements like textbox, button, radio button in a html form. createElement() method is used to create html elements at runtime.
Here is the example:
HTML:
<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">add Button</option>
<option value="text">add Textbox</option>
<option value="radio">add Radio</option>
</select>
<input type="button" value="Add" onclick="add(document.forms[0].element.value)"/>
<span id=elementContent> </span>
</form>
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 cont = document.getElementById("elementContent");
//Append the element in page (in span).
cont.appendChild(element);
}
In the above example, we have a select box with the options to add button, textbook or radio button. When user makes a choice the element will be added in the form.
we have used createElement() to create html elements and setAttribute to assign the different attributes to the dynamically created elements.
You can check the demo here.
0 Comment(s)