1

Jquery を使って Cocoon gem で fields_for 内のフィールドの値を設定したいと考えています。jqueryで変更イベントを使用しています。

_形

<%= form_for(@invoice) do |f| %>

  <div class="field">
    <%= f.label :total_order %><br>
    <%= f.number_field :total_order %>
    <%= f.object_id %>
  </div>
  <div id="items">
    <%= f.fields_for :items do |i| %>
      <%= render 'item_fields', :f => i %>
    <% end %>
    <div class="links">
      <%= link_to_add_association '+ produk', f, :items %>
    </div>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

_item_fields

<div class="nested-fields">
<tr>
    <td><%= f.select :product_id,
                        Product.all.collect {|p| [p.name, p.id, 
                        {'data-unit_cost'=>p.unit_cost}]}, 
                        { include_blank: true },
                        { class: "product-select"} %>
    </td>
    <td><%= f.number_field :unit_cost, 
                    label: false,
                class: "cost-input" %>
    </td> 
    <td><%= f.number_field :quantity,
                    label: false,
                    class: "qty-input" %>
    </td>
    <td style="vertical-align: top;"><%= link_to_remove_association '- remove', f %></td>
</tr>
</div>

コーヒースクリプト

$("#items").on "cocoon:after-insert", ->
    $(".product-select").change ->
        $(".cost-input").val($(".product-select :selected").data("unit_cost"))

問題は、最初のネストされたレコードに対してのみ機能することです。これは、fields_for によって生成される動的 ID に関連している可能性がありますが、対処方法がわかりません。

どんな助けでも大歓迎です。


スクリプトに変更が加えられました。これが私の質問への回答です。

$("#items").on "change", ".product-select", ->
    product_select = $(this)
    product_select.parent().find('.cost-input').val(product_select.find(':selected').data('unit_cost'))

私を助けてくれたnathanvdaに感謝します。

4

1 に答える 1