Created
March 2, 2016 10:41
-
-
Save pokorson/3c612877a68004381a48 to your computer and use it in GitHub Desktop.
JS nested fields form
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Example for haml with one field in NesteIdem, file :image | |
# js adding and removing fields. Edit and destroy nested fields without parent is not covered | |
# Our relation | |
# Parent has many NestedItems, NestedItem belongs to Parent | |
.nested-container | |
.btn.btn-default.add-nested Dodaj więcej zdjęć + | |
.nested-items | |
.nested-item{ data: { index: 0 }} | |
# input tag name will generate nested object in params | |
= file_field_tag :image, id: "parent_nested_items_attributes_0_image", | |
name: "parent[nested_items_attributes][0][image]", | |
type: :file | |
:coffee | |
$('.add-attachment').click (e) -> | |
# easier version, instead of creating whole element by yourself we will just | |
# copy last item and swap attributes | |
$nestedItemEl = $('.nested-items').find('.nested-item').last().clone() # copy last item | |
$inputEl = $nestedItemEl.find('input') # find input inside div | |
index = parseInt($nestedItemEl.data('index')) + 1 # increment nested item index | |
# replace id, name and data-cip-id attributes | |
$inputEl.attr('id', 'parent_nested_items_attributes_' + index + '_image') | |
$inputEl.attr('name', 'parent[nested_items_attributes][' + index + '][image]') | |
$inputEl.attr('data-cip-id', 'parent_nested_items_attributes_' + index + '_image') | |
$invoiceEl.attr('data-index', index) | |
# initial nested item element in DOM doesn't have remove button. Because we | |
# are all the time copy last item we need to append it only to first one | |
if(index == 1) | |
$button = $('<div class="btn btn-danger btn-xs remove-nested-item">usuń</div>') | |
$button.click -> | |
$(this).parent().remove() | |
$invoiceEl.append($button) | |
else | |
$invoiceEl.find('.remove-nested-item').click -> | |
$(this).parent().remove() | |
# append item to container | |
$('.nested-items').append($invoiceEl) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment