Skip to content

Instantly share code, notes, and snippets.

@mikedhart
Created June 4, 2014 09:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mikedhart/0fdba6269c8d38a7bffb to your computer and use it in GitHub Desktop.
Save mikedhart/0fdba6269c8d38a7bffb to your computer and use it in GitHub Desktop.
# 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