Skip to content

Instantly share code, notes, and snippets.

@barriault
Last active August 29, 2015 14:16
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 barriault/1af3a720104743a2b542 to your computer and use it in GitHub Desktop.
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.
# 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()
@barriault
Copy link
Author

DISCLAIMER: I am not a Javascript/Coffescript programmer, so if anyone has a better way to do this please share.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment