A jquery plugin for adding / removing nested form dynamically
npm install @kanety/jquery-nested-formA jquery plugin for adding / removing Rails nested form dynamically.
* jquery
Install from npm:
$ npm install @kanety/jquery-nested-form --save
Build nested form using Rails fields_for as usual:
``erb`
<%= form_with do |f| %>
<%= f.fields_for :assocs do |assoc_form| %>
<%= assoc_form.text_field :text %>
<% end %>
<% end %>
Then run:
`javascript`
$('#container').nestedForm({
forms: '.nested-form',
adder: '#add',
remover: '.remove',
associations: 'assocs'
});
New nested form is added when the #add button is clicked..nested-form
The last elements of the are used as a template to be added.id
The index of and name attributes are incremented automatically.
`html`
associations and postfixes are available for finding the index of the nested form.assocsA
If your nested form consists of multiple associations such as and assocsB, you can set the associations as the following example:
`javascript`
$().nestedForm({
associations: ['assocsA', 'assocsB'],
postfixes: '_attributes'
});
tags and attributes are available to customize the attributes to be replaced:
`javascript`
$().nestedForm({
tags: $.NestedForm.getDefaults().tags.concat(['a']),
attributes: $.NestedForm.getDefaults().attributes.concat(['onclick'])
});
max is useful if you want to disable the add button when the number of nested forms reached to the limit:
`javascript`
$().nestedForm({
max: 10
});
Following callbacks are available to manipulate DOM elements:
`javascript`
$().nestedForm({
afterInitialize: function(instance) {},
onBuildForm: function($form) {},
beforeAddForm: function($container, $form) {},
afterAddForm: function($container, $form) {},
beforeRemoveForm: function($form) {},
afterRemoveForm: function($form) {}
});
If you have multi-level nested form, use nestedForm as follows:
`erb`
<%= form_with do |f| %>
<%= f.fields_for :assocs do |assoc_form| %>
<%= assoc_form.text_field :text %>
<%= assoc_form.fields_for :assocs2 do |assoc2_form| %>
<%= assoc2_form.text_field :text %>
<% end %>
<% end %>
<% end %>
`javascript`
$('#container').nestedForm({
forms: '.nested-form',
adder: '.add',
nestedForm: {
forms: '.deep-nested-form',
adder: '.deep-add'
}
});
The nestedForm` option handles same arguments as the first-level form.
The library is available as open source under the terms of the MIT License.