Jquery를 사용하여 Cocoon gem으로 fields_for 필드의 값을 설정하고 싶습니다. jquery에 change 이벤트를 사용하고 있습니다.fields를 Cocoon 및 Jquery로 업데이트하십시오.
_form
<%= 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에게 감사드립니다.
안녕하세요, 답변 해 주셔서 감사합니다. 클래스로 변경했습니다 (편집 된 코드 참조). 이제 두 번째 행 unit_cost는 첫 번째 행과 동일한 값을 갖습니다. 그래서 세 번째도 마찬가지입니다. – dango
두 번째 답변입니다. 고마워요! 비슷한 문제가있는 모든 사용자를 위해 스크립트를 추가했습니다. – dango