Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
# Handles forms where an infinite amount of fieldsets can be added or removed
#
# @author Mike Hart
# @version 0.2
# @copyright Smaller Earth Tech Ltd
add_remove_item_listener = ->
jQuery('remove_item').unbind 'click'
jQuery('.remove_item').on('click', (event) ->
event.stopPropagation()
jQuery(event.target).closest('.item').find('[name*=_destroy]').val(true)
jQuery(event.target).closest('.item').css('display', 'none')
)
ready = ->
add_remove_item_listener()
jQuery('.add_item').on('click', (event) ->
event.stopPropagation()
jQuery('.item:last').after(jQuery('.item:first').clone())
i = jQuery('div.item').length
jQuery('.item:last input, .item:last select, .item:last textarea').each((index, el) ->
original_name = jQuery(el).attr("name")
new_name = original_name.replace(/\[[0-9]\]/, "[#{ i.toString() }]")
original_id = jQuery(el).attr("id")
new_id = original_id.replace(/_[0-9]_/, "_#{ i.toString() }_")
if ($(el).attr("type") != "hidden")
jQuery(el).val('').attr('name', new_name)
jQuery(el).val('').attr('id', new_id)
else
jQuery(el).attr('name', new_name)
jQuery(el).attr('id', new_id)
)
add_remove_item_listener()
)
jQuery(document).on('ready page:load', ready)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.