Reputation: 1117
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.
Upvotes: 0
Views: 4790
Reputation: 38345
There are two specific issues.
IDs are supposed to be unique. Having an anchor with an id of addAttribute
for every person isn't valid, and only the first element found in the DOM will have the event bound. This isn't a problem at the start because there's only one of them, but does become a problem later on once you start adding additional family members.
Events bound in the ready handler are only bound to elements that exist when the code executes. If you're going to be adding new elements that you want to have those events bound you need to use event delegation:
$(document).on('click', '.addAttribute', function() {
// add an attribute here
// I've changed from an ID to a class selector
// you'll need to find a way to get a reference to the correct elements from a specific anchor
});
I've put together a demo with the changes detailed above.
Upvotes: 4