【问题标题】:jQuery on multiple nested fields only working on first多个嵌套字段上的 jQuery 仅适用于第一个
【发布时间】:2016-12-19 00:22:33
【问题描述】:

由于我在这方面的薄弱,我再次寻求有关 jQueries 的帮助。每当通过 collection_select 下拉菜单选择 product_id 时,我已经在我的订单表单上成功实现了 jQuery,以便在文本字段中显示 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。提前致谢!!

有人可以帮我吗?

【问题讨论】:

    标签: javascript jquery ruby-on-rails ruby-on-rails-4 coffeescript


    【解决方案1】:

    您需要为该类运行每个以访问与同一类关联的所有元素。喜欢 -

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

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

    或者你可以使用 -

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

    【讨论】:

    • 我已将您的建议实施到我的代码中,但没有任何改变。还有其他解决方案吗?无论如何感谢您的帮助
    • 在dom中添加元素后需要调用该函数。
    猜你喜欢
    • 2015-12-12
    • 1970-01-01
    • 2018-08-19
    • 2013-01-11
    • 2011-08-25
    • 2012-06-12
    • 1970-01-01
    • 1970-01-01
    • 2012-12-13
    相关资源
    最近更新 更多