Skip to content

Instantly share code, notes, and snippets.

@dkln
Created January 21, 2011 14:47
Show Gist options
  • Save dkln/789764 to your computer and use it in GitHub Desktop.
Save dkln/789764 to your computer and use it in GitHub Desktop.
Easy adding/removing in nested forms for simple_form (javascript)
var Forms = {
generatedId: function() {
return String(new Date().getTime());
},
applyAddFieldsBehaviour: function() {
var self = this;
$('.add_fields[data-content]').each(self._applyAddFieldBehaviour);
},
applyDestroyFieldsBehaviour: function() {
var self = this;
$('.destroy_fields').each(self._applyDestroyFieldBehaviour);
},
_applyAddFieldBehaviour: function() {
var element = $(this);
if(!element.hasAddFieldsBehaviour) {
element.hasAddFieldsBehaviour = true;
element.click(Forms._handleAddClick);
}
},
_applyDestroyFieldBehaviour: function() {
var element = $(this);
if(!element.hasDestroyFieldsBehaviour) {
element.hasDestroyFieldsBehaviour = true;
element.click(Forms._handleDestroyClick);
}
},
_handleAddClick: function(event) {
var button = $(event.currentTarget);
var nav = button.closest('nav')
nav.before(Forms._htmlForNewRecord(button));
event.preventDefault();
Forms.applyDestroyFieldsBehaviour();
},
_htmlForNewRecord: function(addButton) {
html = addButton.attr('data-content');
html = html.replace(/_new_/g, '_' + Forms.generatedId() + '_');
html = html.replace(/\[new\]/g, '[' + Forms.generatedId() + ']');
return html;
},
_handleDestroyClick: function(event) {
var button = $(event.currentTarget);
var form = button.closest('form');
var fieldset = button.closest('fieldset');
var idField = fieldset.next('input[type=hidden]');
form.append('<input type="hidden" name="' + button.attr('data-id') + '[_destroy]" value="1">');
fieldset.remove();
event.preventDefault();
}
}
$(function() {
Forms.applyAddFieldsBehaviour();
Forms.applyDestroyFieldsBehaviour();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment