Dynamically add elements to form
Dynamically add button, textbox, input, radio elements in html form using JavaScript. http://viralpatel.net/blogs/2009/01/dynamic-add-textbox-input-button-radio-element-html-javascript.html
by Andy Bulka
HTML
<FORM>
<H2>Dynamically add elements to 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" id="btn_addOpt" onclick="add(document.forms[0].element.value)"/>
<span id="fooBar"> </span>
</FORM>
<h3>
<br />
Re Javascript loading sequence in jsfiddle</h3>
<p>
Look at <a href="http://jsfiddle.net/draft/">http://jsfiddle.net/draft/</a> to see what source is generated to debug when the wiring ain't working<br />
Ensure you load the javascript at the right point see jsfiddle doco <a href="http://doc.jsfiddle.net/basic/introduction.html">here</a>.</p>
<h3>
Re adding and removing dynamically</h3>
<p>
See also <a href="http://stackoverflow.com/questions/7958634/to-addremove-nestedtwo-level-input-elements-dynamically">http://stackoverflow.com/questions/7958634/to-addremove-nestedtwo-level-input-elements-dynamically</a><br />
And <a href="http://www.dustindiaz.com/add-remove-elements-reprise/">http://www.dustindiaz.com/add-remove-elements-reprise/</a><br />
<a href="http://www.erikoest.dk/js_eval.htm">http://www.erikoest.dk/js_eval.htm</a> doesn't work<br />
<a href="http://www.w3schools.com/jsref/jsref_eval.asp">http://www.w3schools.com/jsref/jsref_eval.asp</a> works</p>
<p>
<a href="http://viralpatel.net/blogs/2009/01/dynamic-add-textbox-input-button-radio-element-html-javascript.html">http://viralpatel.net/blogs/2009/01/dynamic-add-textbox-input-button-radio-element-html-javascript.html</a> original idea</
<br />
<br />
<br />
</p>
CSS
h1 { font-size: 2em; margin: .67em 0 }
h2 { font-size: 1.5em; margin: .75em 0 }
h3 { font-size: 1.17em; margin: .83em 0 }
JavaScript
// this wiring doesn't work - unless you load the jsfiddle javascript AFTER the html body - using the "no wrap (body)" options
function add(type) {
//alert('ggggg');
//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);
}
// this wiring does
$(document).ready(function() {
$('#btn_addOpt').click(function () {
var opt = $('<div></div>');
opt.append('<p>Answer:</p>');
opt.append('<input type="text" name="zz">');
$('#fooBar').append(opt);
});
/*
$('#btn_removeOpt').click(function () {
$('#opt div:last').remove();
});
*/
});