Skip to content

Instantly share code, notes, and snippets.

@thoas
Created February 11, 2014 15:44
Show Gist options
  • Save thoas/8937406 to your computer and use it in GitHub Desktop.
Save thoas/8937406 to your computer and use it in GitHub Desktop.
var FormSet = function (form, prefix) {
this.$form = $(form);
this.prefix = prefix;
}
FormSet.prototype.updateElementIndex = function (el, ndx) {
var regex = new RegExp('(' + this.prefix + '-\\d+-)'),
replacement = this.prefix + '-' + ndx + '-',
element = $(el);
if (element.attr('for')) {
element.attr('for', element.attr('for').replace(regex, replacement));
}
if (element.attr('id')) {
element.attr('id', element.attr('id').replace(regex, replacement));
}
if (element.attr('name')) {
element.attr('name', element.attr('name').replace(regex, replacement));
}
}
FormSet.prototype.count = function (count) {
var key = '#id_' + this.prefix + '-TOTAL_FORMS',
el = $(key);
if (count === undefined) {
return parseInt(el.val(), 10);
}
el.val(count);
}
FormSet.prototype.remove = function (btn, callback) {
var formCount = this.count();
if (formCount < 1) {
return;
}
var parent = $(btn).parents('.item:first'),
hidden = parent.find('input[type=checkbox][name*="DELETE"]'),
forms = this.$form.find('.item'),
i = 0,
_this = this;
if (hidden.length) {
hidden.prop('checked', true);
parent.hide();
} else {
parent.remove();
this.count(forms.length);
for (formCount = forms.length; i < formCount; i++) {
$(forms.get(i)).children().children().each(function () {
if ($(this).attr('type') == 'text') {
_this.updateElementIndex(this, i);
}
});
}
}
if (callback !== undefined) {
callback(forms);
}
}
FormSet.prototype.add = function (btn, callback) {
var formCount = this.count(),
last = this.$form.find('.item:last'),
row = last.clone(false).get(0),
_this = this;
$(row).removeAttr('id').hide().insertAfter(last).slideDown(300);
$('.errorlist', row).remove();
$(row).find('input,textarea,select').each(function () {
_this.updateElementIndex($(this), formCount);
$(this).val('');
});
$(row).find('.delete').click(function () {
return _this.remove($(this));
});
_this.count(formCount + 1);
if (callback !== undefined) {
callback(row);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment