Last active
August 29, 2015 14:16
-
-
Save barriault/1af3a720104743a2b542 to your computer and use it in GitHub Desktop.
An easy way to add a link to a form that changes the submit action from the default format to .pdf, .csv, etc. and then submits the 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
# Function allows you to change the action of a form when clicking a link. This comes | |
# in handy when you want to change the format of a form from its default to .csv, .pdf | |
# or something other than the default. This is also set up to work outside of the | |
# <form></form> tag. | |
# | |
# Typical use: | |
# | |
# <%= link_to '#', data: { behavior: "dynamicsubmitable", target: "#form_id", link: resource_path(format: :pdf) } %> | |
# | |
$ = jQuery | |
$.fn.extend | |
dynamicSubmitable: -> | |
$(@).each (i, el) -> | |
new DynamicSubmitable($(el)) | |
class DynamicSubmitable | |
constructor: ($a) -> | |
@init($a) | |
init: ($a) -> | |
$a.on "click", -> | |
link = $a.data('link') | |
targetFormId = $a.data('target') | |
old_action = $(targetFormId).attr('action') | |
$(targetFormId).attr('action', link) | |
$(targetFormId).submit() | |
$(targetFormId).attr('action', old_action) | |
jQuery -> | |
$("[data-behavior~='dynamicsubmitable']").dynamicSubmitable() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
DISCLAIMER: I am not a Javascript/Coffescript programmer, so if anyone has a better way to do this please share.