jQuery对多个嵌套字段只工作在第一

jQuery on multiple nested fields only working on first

本文关键字:工作 字段 嵌套 jQuery      更新时间:2023-09-26

我再次寻求jQueries的帮助,因为我在这方面很弱。我已经成功地在我的订单上实现了jQuery,当通过collection_select下拉菜单选择product_id时,在文本字段中显示product:price。

我的表格如下:

<%= form_for(@order) do |f| %>
.
.
.
<%= f.add_nested_fields_link :single_orders, "Add Product" %>
<%= f.nested_fields_for :single_orders do |builder| %>
  <div class = "form-inline">
    <%= builder.collection_select :product_id, @products, :id, :select_product, {:prompt => "choose product"}, {:class => "product_selection form-control"}  %>
    <%= builder.text_field :ctn_price, placeholder: "Price/carton", id: "ctn_price", readonly: true, class: 'ctn_price_field form-control' %>
    <%= builder.text_field :qty, placeholder: "Quantity",id: "quantity", class: 'form-control' %>
    <%= builder.text_field :price, placeholder: "Amount", id: "amount", readonly: true, class: 'form-control' %>
    <%= builder.remove_nested_fields_link %>
  </div>
<% end %>
.
.
.
<%= f.submit "place order", class: "btn btn-primary" %>
<% end %>

我可以通过jQuery通过orders.js.coffee文件获取product_prices

jQuery ->
  $(".product_selection").on "change", ->
      $.ajax
        url: "/orders/get_product_prices"
        type: "GET"
        dataType: "script"
        data:
          product_id: $('.product_selection option:selected').val()

并使用get_product_prices.js.erb

显示它
$('.ctn_price_field').val(<%= @product.price %>)    

一切都在工作接受,当我添加超过1个嵌套字段,jQuery似乎只能检测第一个嵌套字段,只改变第一个。ctn_price_field我想要完成的是在同一个表单中生成多个嵌套字段,并能够根据所选产品更改每个nested_field:price。提前感谢!!

有人能帮我吗?

您需要运行每个类来访问与同一类关联的所有元素。Like -

$(".product_selection").each(function() {
    // ...
});

并确保在HTML中绑定元素后调用此绑定。

或者使用-

$('.product_selection').change(function(){
   // code goes here
});