joseph.hainline
joseph.hainline

Reputation: 26608

Capture submit button with coffeescript for multiple forms

I'm trying to capture the submit button on a form, and do some processing (in this case, send credit card data to Stripe). I've got an Order class, and when the new order submit button is pressed, it captures the submit and sends it to my captureSubmitForStripe method. That part is working great, and here is a code snippet:

# orders.js.coffee:
jQuery ->
  Stripe.setPublishableKey($('meta[name="stripe-key"]').attr('content'))
  order.setupForm()

order =
  setupForm: ->
    $('#new_order').submit ->
      order.captureSubmitForStripe()

  captureSubmitForStripe: ->
    # do more stuff here...

I'd like to make this work for the submit button on the edit form as well. How do I write this so it captures the submit button from whatever form I'm in, or at least from both the new and edit forms?

I've tried this, among other things, and it doesn't work:

order =
  setupForm: ->
    $('#new_order').submit ->
      order.captureSubmitForStripe()
    $('#edit_order').submit ->
      order.captureSubmitForStripe()

Upvotes: 0

Views: 1343

Answers (1)

jvnill
jvnill

Reputation: 29599

You don't have issues with using $('#new_order') because that's the default id of the form when you use form_for for new objects. For persisted objects, the id becomes edit_order_123 where 123 is the id of the object. I suggest you use a class for both the new and edit forms

# set the class
form_for @order, html: { class: 'order-form' } do
  ...

# then just use the class to select the form
$('.order-form').submit -> order.captureSubmitForStripe()

Upvotes: 1

Related Questions