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 insertDeleteLink(row);
121 applyExtraClasses(row, i);
125 if ((options.parent && options.addLinkParent) || $$.length) {
126 var hideAddButton = !showAddButton(),
128 if (options.formTemplate) {
129 // If a form template was specified, we'll clone it to generate new form instances:
130 template = (options.formTemplate instanceof $) ? options.formTemplate : $(options.formTemplate);
131 template.removeAttr('id').addClass(options.formCssClass + ' formset-custom-template');
132 template.find(childElementSelector).each(function() {
133 updateElementIndex($(this), options.prefix, '__prefix__');
135 insertDeleteLink(template);
137 // Otherwise, use the last form in the formset; this works much better if you've got
138 // extra (>= 1) forms (thnaks to justhamade for pointing this out):
139 template = $('.' + options.formCssClass + ':last').clone(true).removeAttr('id');
140 template.find('input:hidden[id $= "-DELETE"]').remove();
141 // Clear all cloned fields, except those the user wants to keep (thanks to brunogola for the suggestion):
142 template.find(childElementSelector).not(options.keepFieldValues).each(function() {
144 // If this is a checkbox or radiobutton, uncheck it.
145 // This fixes Issue 1, reported by Wilson.Andrew.J:
146 if (elem.is('input:checkbox') || elem.is('input:radio')) {
147 elem.attr('checked', false);
153 // FIXME: Perhaps using $.data would be a better idea?
154 options.formTemplate = template;
156 if (options.addLinkParent) {
157 addButton = $('<a class="' + options.addCssClass + '" href="javascript:void(0)">' + options.addText + '</a>');
158 addButton.appendTo(options.addLinkParent);
159 if (hideAddButton) addButton.hide();
160 } else if ($$.is('TR')) {
161 // If forms are laid out as table rows, insert the
162 // "add" button in a new table row:
163 var numCols = $$.eq(0).children().length, // This is a bit of an assumption :|
164 buttonRow = $('<tr><td colspan="' + numCols + '"><a class="' + options.addCssClass + '" href="javascript:void(0)">' + options.addText + '</a></tr>')
165 .addClass(options.formCssClass + '-add');
166 $$.parent().append(buttonRow);
167 if (hideAddButton) buttonRow.hide();
168 addButton = buttonRow.find('a');
170 // Otherwise, insert it immediately after the last form:
171 $$.filter(':last').after('<a class="' + options.addCssClass + '" href="javascript:void(0)">' + options.addText + '</a>');
172 addButton = $$.filter(':last').next();
173 if (hideAddButton) addButton.hide();
175 addButton.click(function() {
176 var formCount = parseInt(totalForms.val()),
177 row = options.formTemplate.clone(true).removeClass('formset-custom-template'),
178 buttonRow = $($(this).parents('tr.' + options.formCssClass + '-add').get(0) || this);
179 applyExtraClasses(row, formCount);
181 row.appendTo(options.parent).show();
183 row.insertBefore(buttonRow).show();
185 row.find(childElementSelector).each(function() {
186 updateElementIndex($(this), options.prefix, formCount);
188 totalForms.val(formCount + 1);
189 // Check if we've exceeded the maximum allowed number of forms:
190 if (!showAddButton()) buttonRow.hide();
191 // If a post-add callback was supplied, call it with the added form:
192 if (options.added) options.added(row);
200 /* Setup plugin defaults */
201 $.fn.formset.defaults = {
202 prefix: 'form', // The form prefix for your django formset
203 formTemplate: null, // The jQuery selection cloned to generate new form instances
204 parent: null, // The jQuery selection to insert new forms
205 addText: 'add another', // Text for the add link
206 deleteText: 'remove', // Text for the delete link
207 addLinkParent: null, // The jQuery selection to insert add link
208 addCssClass: 'add-row', // CSS class applied to the add link
209 deleteCssClass: 'delete-row', // CSS class applied to the delete link
210 formCssClass: 'dynamic-form', // CSS class applied to each form in a formset
211 extraClasses: [], // Additional CSS classes, which will be applied to each form in turn
212 keepFieldValues: '', // jQuery selector for fields whose values should be kept when the form is cloned
213 added: null, // Function called each time a new form is added
214 removed: null // Function called each time a form is deleted