Last active
January 15, 2018 08:23
-
-
Save hguochen/8955282 to your computer and use it in GitHub Desktop.
Django formset with ajax
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<h3>My Services</h3> | |
{{ serviceFormset.management_form }} | |
{% for form in serviceFormset.forms %} | |
<div class='table'> | |
<table class='no_error'> | |
{{ form.as_table }} | |
</table> | |
</div> | |
{% endfor %} | |
<input type="button" value="Add More" id="add_more"> | |
<script> | |
$('#add_more').click(function() { | |
cloneMore('div.table:last', 'service'); | |
}); | |
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; | |
$(this).attr({'name': name, 'id': id}).val('').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); | |
} | |
</script> | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment