-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdjango-formsets.jquery.js
More file actions
68 lines (61 loc) · 2.87 KB
/
Copy pathdjango-formsets.jquery.js
File metadata and controls
68 lines (61 loc) · 2.87 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
(function($){
$.fn.formset = function(options){
var options = $.extend({}, $.fn.formset.defaults, options)
var container = this;
var addButtonId = options.prefix + '-' + options.addCssClass;
var addLink = '<a id="' + addButtonId + '" class="' + options.addCssClass + '" href="javascript:void(0);">' + options.addText + '</a>';
var removeButtonId = options.prefix + '-' + options.removeCssClass;
var removeLink = '<a id="' + removeButtonId + '" class="' + options.removeCssClass + '" href="javascript:void(0);">' + options.removeText + '</a>';
container.append(addLink)
container.find('> div:not(:first)').hide();
addButton = $('#' + addButtonId);
addForm = function(){
// Every time the link is clicked, show another form and add a remove link
newForm = $(this).siblings('div:hidden').first();
newForm.show();
newForm.after(removeLink);
// Remove add link if we're at the maximum number of forms
formCount = container.find(' > div:visible').length;
maxFormCount = parseInt($('#id_' + options.prefix + '-TOTAL_FORMS').val());
if (formCount == maxFormCount) {
$(this).remove();
}
// Remove a form when we click on its remove link
removeButtons = $('.' + options.removeCssClass);
removeButtons.click(removeForm);
};
removeForm = function(){
// Clear forms before hiding them so they don't get validated
$(this).prev()
.find(':input')
.val('')
.removeAttr('checked')
.removeAttr('selected');
$(this).prev().hide();
// If we are removing the last of the buttons, we'll need to put the add button back in
formCount = container.find(' > div:visible').length;
maxFormCount = parseInt($('#id_' + options.prefix + '-TOTAL_FORMS').val());
if (formCount != maxFormCount) {
if ($('#' + addButtonId).length == 0) {
container.append(addLink);
addButton = $('#' + addButtonId);
addButton.click(addForm);
}
}
$(this).remove();
};
addButton.click(addForm);
// If some of the formsets have data, we need to show them.
inputs = container.find('[id^="id_' + options.prefix + '"]')
inputs.each(function(){
if ($(this).val()) {
console.log($(this).parents('.form'))
$(this).parents('.form').show().each(function(){
$(this).after(removeLink);
removeButtons = $('.' + options.removeCssClass);
removeButtons.click(removeForm);
});
}
});
};
})(jQuery)