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

2

您使用元素 ID。它在 HTML 页面中应该是唯一的。您应该改用类。

[更新]好的。您使用全局选择器,因此您更改所有具有该类的元素。

我猜你真正想要的是改变刚刚插入的元素。如文档中所示,这是可能的。写吧

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

此代码未经测试,但我所做的:附加change事件。在 change 事件中, use $(this),它指向触发事件的容器,并将其用作查找所需项目的相对点。

请注意,如果您只使用 jquery,这更容易解决。

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

这将捕获发生在元素上的所有change事件。这是动态的,因此它也适用于新添加的项目。您可能需要稍微摆弄一下 jquery 才能找到选定的值。正如我所说:未经测试的代码,但我希望你能理解。#items.product-select

于 2014-05-13T09:49:31.873 回答