After reading @Paolo Bergantino's response to this specific question on SO, I have been attempting to dynamically include forms in my formset. However, I've noticed that the newly added form appears to be somehow connected to the previous one. When I click a checkbox on the new form, it affects the old form as well. Furthermore, when I submit, only one form is shown in the post. What happens to all the other newly added forms?
addAnother.js
function cloneMore(selector, type) {
var newElement = $(selector).clone(true);
var total = $('#id_' + type + '-TOTAL_FORMS').val();
newElement.find(':input').each(function() {
var name = $(this).attr('name').replace('-' + (total-1) + '-','-' + total + '-');
var id = 'id_' + name;
if ($(this).attr('type') != 'hidden') {
$(this).val('');
}
$(this).attr({'name': name, 'id': id}).removeAttr('checked');
});
newElement.find('label').each(function() {
var newFor = $(this).attr('for').replace('-' + (total-1) + '-','-' + total + '-');
$(this).attr('for', newFor);
});
total++;
$('#id_' + type + '-TOTAL_FORMS').val(total);
$(selector).after(newElement);
}
template.html
{% load crispy_forms_tags %}
<script src="{{ STATIC_URL }}js/addAnother.js" type="text/javascript"></script>
<form action="{% url 'databank:register' %}" method="post" enctype="multipart/form-data">
<div class="container">
<div class="row" style="margin-top: 30px">
<div class="col-md-10 col-md-offset-1">
{{ dataset_form.media }}
{% crispy dataset_form %}
{% crispy facility_form %}
{% crispy contact_form %}
{{ author_formset.management_form }}
{% for form in author_formset.forms %}
<div class='table'>
<table class='no_error'>
{{ form.as_table }}
</table>
</div>
{% endfor %}
<input type="button" value="Add More" id="add_more">
{% crispy terms_form %}
</div>
</div>
</div>
<div class="container">
<div class="row">
<div class="col-md-10 col-md-offset-1">
<a role="button" class="btn btn-lg btn-default" href="{% url 'databank:databank_home' %}">Cancel</a>
<input type="submit" class="btn btn-lg btn-success pull-right" value="Proceed to Data Upload">
</div>
</div>
</div>
</form>
<script type="text/javascript">
$('#add_more').click(function() {
cloneMore('div.table:last', 'service');
});