2 * jQuery Formset 1.3-pre
3 * @author Stanislaus Madueke (stan DOT madueke AT gmail DOT com)
4 * @requires jQuery 1.2.6 or later
6 * Copyright (c) 2009, Stanislaus Madueke
9 * Licensed under the New BSD License
10 * See: http://www.opensource.org/licenses/bsd-license.php
13 $.fn.formset = function(opts)
15 var options = $.extend({}, $.fn.formset.defaults, opts),
16 flatExtraClasses = options.extraClasses.join(' '),
17 totalForms = $('#id_' + options.prefix + '-TOTAL_FORMS'),
18 maxForms = $('#id_' + options.prefix + '-MAX_NUM_FORMS'),
19 childElementSelector = 'input,select,textarea,label,div',
22 applyExtraClasses = function(row, ndx) {
23 if (options.extraClasses) {
24 row.removeClass(flatExtraClasses);
25 row.addClass(options.extraClasses[ndx % options.extraClasses.length]);
29 updateElementIndex = function(elem, prefix, ndx) {
30 var idRegex = new RegExp(prefix + '-(\\d+|__prefix__)-'),
31 replacement = prefix + '-' + ndx + '-';
32 if (elem.attr("for")) elem.attr("for", elem.attr("for").replace(idRegex, replacement));
33 if (elem.attr('id')) elem.attr('id', elem.attr('id').replace(idRegex, replacement));
34 if (elem.attr('name')) elem.attr('name', elem.attr('name').replace(idRegex, replacement));
37 hasChildElements = function(row) {
38 return row.find(childElementSelector).length > 0;
41 showAddButton = function() {
42 return maxForms.length == 0 || // For Django versions pre 1.2
43 (maxForms.val() == '' || (maxForms.val() - totalForms.val() > 0));
46 insertDeleteLink = function(row) {
47 var delCssSelector = options.deleteCssClass.trim().replace(/\s+/g, '.'),
48 addCssSelector = options.addCssClass.trim().replace(/\s+/g, '.');
50 // If the forms are laid out in table rows, insert
51 // the remove button into the last table cell:
52 row.children(':last').append('<a class="' + options.deleteCssClass +'" href="javascript:void(0)">' + options.deleteText + '</a>');
53 } else if (row.is('UL') || row.is('OL')) {
54 // If they're laid out as an ordered/unordered list,
55 // insert an <li> after the last list item:
56 row.append('<li><a class="' + options.deleteCssClass + '" href="javascript:void(0)">' + options.deleteText +'</a></li>');
58 // Otherwise, just insert the remove button as the
59 // last child element of the form's container:
60 row.append('<a class="' + options.deleteCssClass + '" href="javascript:void(0)">' + options.deleteText +'</a>');
62 row.find('a.' + delCssSelector).click(function() {
63 var row = $(this).parents('.' + options.formCssClass),
64 del = row.find('input:hidden[id $= "-DELETE"]'),
65 buttonRow = row.siblings("a." + addCssSelector + ', .' + options.formCssClass + '-add'),
68 // We're dealing with an inline formset.
69 // Rather than remove this form from the DOM, we'll mark it as deleted
70 // and hide it, then let Django handle the deleting:
73 forms = $('.' + options.formCssClass).not(':hidden');
76 // Update the TOTAL_FORMS count:
77 forms = $('.' + options.formCssClass).not('.formset-custom-template');
78 totalForms.val(forms.length);
80 for (var i=0, formCount=forms.length; i<formCount; i++) {
81 // Apply `extraClasses` to form rows so they're nicely alternating:
82 applyExtraClasses(forms.eq(i), i);
84 // Also update names and IDs for all child controls (if this isn't
85 // a delete-able inline formset) so they remain in sequence:
86 forms.eq(i).find(childElementSelector).each(function() {
87 updateElementIndex($(this), options.prefix, i);
91 // Check if we need to show the add button:
92 if (buttonRow.is(':hidden') && showAddButton()) buttonRow.show();
93 // If a post-delete callback was provided, call it with the deleted form:
94 if (options.removed) options.removed(row);
101 del = row.find('input:checkbox[id $= "-DELETE"]');
103 // If you specify "can_delete = True" when creating an inline formset,
104 // Django adds a checkbox to each form in the formset.
105 // Replace the default checkbox with a hidden field:
106 if (del.is(':checked')) {
107 // If an inline formset containing deleted forms fails validation, make sure
108 // we keep the forms hidden (thanks for the bug report and suggested fix Mike)
109 del.before('<input type="hidden" name="' + del.attr('name') +'" id="' + del.attr('id') +'" value="on" />');
112 del.before('<input type="hidden" name="' + del.attr('name') +'" id="' + del.attr('id') +'" />');
114 // Hide any labels associated with the DELETE checkbox:
115 $('label[for="' + del.attr('id') + '"]').hide();
118 if (hasChildElements(row)) {
119 row.addClass(options.formCssClass);
120 if (row.is(':visible')) {
121 insertDeleteLink(row);
122 applyExtraClasses(row, i);
127 if ((options.parent && options.addLinkParent) || $$.length) {
128 var hideAddButton = !showAddButton(),
130 if (options.formTemplate) {
131 // If a form template was specified, we'll clone it to generate new form instances:
132 template = (options.formTemplate instanceof $) ? options.formTemplate : $(options.formTemplate);
133 template.removeAttr('id').addClass(options.formCssClass + ' formset-custom-template');
134 template.find(childElementSelector).each(function() {
135 updateElementIndex($(this), options.prefix, '__prefix__');
137 insertDeleteLink(template);
139 // Otherwise, use the last form in the formset; this works much better if you've got
140 // extra (>= 1) forms (thnaks to justhamade for pointing this out):
141 template = $('.' + options.formCssClass + ':last').clone(true).removeAttr('id');
142 template.find('input:hidden[id $= "-DELETE"]').remove();
143 // Clear all cloned fields, except those the user wants to keep (thanks to brunogola for the suggestion):
144 template.find(childElementSelector).not(options.keepFieldValues).each(function() {
146 // If this is a checkbox or radiobutton, uncheck it.
147 // This fixes Issue 1, reported by Wilson.Andrew.J:
148 if (elem.is('input:checkbox') || elem.is('input:radio')) {
149 elem.attr('checked', false);
155 // FIXME: Perhaps using $.data would be a better idea?
156 options.formTemplate = template;
158 if (options.addLinkParent) {
159 addButton = $('<a class="' + options.addCssClass + '" href="javascript:void(0)">' + options.addText + '</a>');
160 addButton.appendTo(options.addLinkParent);
161 if (hideAddButton) addButton.hide();
162 } else if ($$.is('TR')) {
163 // If forms are laid out as table rows, insert the
164 // "add" button in a new table row:
165 var numCols = $$.eq(0).children().length, // This is a bit of an assumption :|
166 buttonRow = $('<tr><td colspan="' + numCols + '"><a class="' + options.addCssClass + '" href="javascript:void(0)">' + options.addText + '</a></tr>')
167 .addClass(options.formCssClass + '-add');
168 $$.parent().append(buttonRow);
169 if (hideAddButton) buttonRow.hide();
170 addButton = buttonRow.find('a');
172 // Otherwise, insert it immediately after the last form:
173 $$.filter(':last').after('<a class="' + options.addCssClass + '" href="javascript:void(0)">' + options.addText + '</a>');
174 addButton = $$.filter(':last').next();
175 if (hideAddButton) addButton.hide();
177 addButton.click(function() {
178 var formCount = parseInt(totalForms.val()),
179 row = options.formTemplate.clone(true).removeClass('formset-custom-template'),
180 buttonRow = $($(this).parents('tr.' + options.formCssClass + '-add').get(0) || this);
181 applyExtraClasses(row, formCount);
183 row.appendTo(options.parent).show();
185 row.insertBefore(buttonRow).show();
187 row.find(childElementSelector).each(function() {
188 updateElementIndex($(this), options.prefix, formCount);
190 totalForms.val(formCount + 1);
191 // Check if we've exceeded the maximum allowed number of forms:
192 if (!showAddButton()) buttonRow.hide();
193 // If a post-add callback was supplied, call it with the added form:
194 if (options.added) options.added(row);
202 /* Setup plugin defaults */
203 $.fn.formset.defaults = {
204 prefix: 'form', // The form prefix for your django formset
205 formTemplate: null, // The jQuery selection cloned to generate new form instances
206 parent: null, // The jQuery selection to insert new forms
207 addText: 'add another', // Text for the add link
208 deleteText: 'remove', // Text for the delete link
209 addLinkParent: null, // The jQuery selection to insert add link
210 addCssClass: 'add-row', // CSS class applied to the add link
211 deleteCssClass: 'delete-row', // CSS class applied to the delete link
212 formCssClass: 'dynamic-form', // CSS class applied to each form in a formset
213 extraClasses: [], // Additional CSS classes, which will be applied to each form in turn
214 keepFieldValues: '', // jQuery selector for fields whose values should be kept when the form is cloned
215 added: null, // Function called each time a new form is added
216 removed: null // Function called each time a form is deleted