I followed this example How to use jQuery to add form elements dynamically
Is it possible to add form elements dynamically to the dynamically generated form?
This is my code:
<html>
<script src="jquery.js" type="text/javascript"></script>
<script>
$(document).ready(function () {
$('#addRow').click(function () {
$('<div/>', {
'class' : 'extraPerson', html: GetHtml()
}).hide().appendTo('#container').slideDown('slow');
});
$('#addAttribte').click(function () {
$('<div/>', {
'class' : 'extraAttribute', html: GetHtml1()
}).hide().appendTo('#extraAttribute').slideDown('slow');
});
})
function GetHtml() {
var len = $('.extraPerson').length;
var $html = $('.extraPersonTemplate').clone();
$html.find('[name=firstname]')[0].name="firstname" + len;
return $html.html();
}
function GetHtml1() {
var len = $('.extraAttribute').length;
var $html = $('.extraAttributeTemplate').clone();
$html.find('[name=attribute]')[0].name="attribute" + len;
return $html.html();
}
</script>
<div class="extraPersonTemplate">
<input class="span3" placeholder="First Name" type="text" name="firstname">
<a href="javascript:void(0)" id="addAttribute">Add Attribute</a>
<div id="extraAttribute"></div>
</div>
<div class="extraAttributeTemplate">
<input class="span3" placeholder="Attribute" type="text" name="attribute">
</div>
<div id="container"></div>
<a href="#" id="addRow"><i class="icon-plus-sign icon-white"></i> Add another family member</p></a>
</html>
I realise there will be issues regarding names of the newly added form elements, but at this point I just want to be able to dynamically add even just a line of text to a dynamically generated form.
Edit: Sorry, forgot to mention what the problem was; the page starts off with just a link saying "Add another family member". This will add the extraPersonTemplate
. This template also has a "Add Attribute" link which adds an extra form field to this newly added field.
However when I click "Add Attribute", I'd expect it to add extraAttributeTemplate
to the bottom of the dynamically added form, but nothing happens.