Created
September 16, 2013 18:29
-
-
Save mkoryak/6584548 to your computer and use it in GitHub Desktop.
submit multiple forms as if it was a single 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
$(-> | |
$doc = $(document) | |
$doc.on('submit', 'form[data-parent]', (e) -> | |
$target = $(e.currentTarget) | |
# we have 2 options here: | |
# 1) find all these sub forms on page load | |
# 2) find them all on each form submit | |
# I like option 2 better because it works with dynamically added/removed forms, at the slight cost of running more selectors | |
parentSelector = $target.data('parent') | |
$parentForm = $(parentSelector) #the attribute must be a selector. Maybe add a sanity check for it being a selector so jquery doesnt barf if its not? | |
if $parentForm.length == 1 | |
e.preventDefault() #if there is no parent form, then this form will submit as usual | |
$forms = $doc.find("form[data-parent='#{parentSelector}']") | |
valid = true | |
_.each($forms, (form) -> | |
if not $(form).valid() | |
valid = false | |
) | |
if valid and $parentForm.valid() | |
formData = $forms.serializeArray() | |
$hiddens = $parentForm.find('input[type=hidden].childForm') | |
_.each(formData, (obj) -> | |
$hidden = $hiddens.find("[name='#{obj.name}']") | |
if $hidden.length == 0 | |
$hidden = $("<input type='hidden' name='#{obj.name}' class='childForm'/>") | |
$parentForm.append($hidden) | |
$hiddens.add($hidden) #prevent us from having duplicate names in a form, if we change this, remember that if the input exists in the parent form that behavior also needs changing | |
$hidden.val(obj.value) | |
) | |
$parentForm.submit() | |
) | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
requires:
underscore, jquery.validate