使用coffeescript捕获提交按钮以获取多个表单

时间:2013-02-04 05:44:40

标签: javascript ruby-on-rails forms coffeescript

我正在尝试捕获表单上的提交按钮,并进行一些处理(在这种情况下,将信用卡数据发送到Stripe)。我有一个Order类,当按下新订单提交按钮时,它会捕获提交并将其发送到我的captureSubmitForStripe方法。这部分工作得很好,这是一段代码片段:

# 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...

我也想在 编辑 表单上的提交按钮上工作。我如何写这个,以便从我所处的任何形式,或者至少从新形式和编辑形式中捕获提交按钮?

我已尝试过这个,除此之外,它不起作用:

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

1 个答案:

答案 0 :(得分:1)

使用$('#new_order')时没有问题,因为当您对新对象使用form_for时,这是表单的默认ID。对于持久化对象,id变为edit_order_123,其中123是对象的id。我建议你为新表格和编辑表格使用一个类

# 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()