0

我有一个“销售”表格,我使用 fields_for 来放置有关要销售的产品的信息。

这是我的 fields_for 表单:

<%= f.fields_for :sellproducts do |c| %>
    <%= c.label :product %> <%= c.grouped_collection_select :product_id, Category.order(:name), :products, :name, :id, :name, :include_blank => true  %>
    <%= c.label :quantity %> <%= c.text_field :quantity, :size =>"5" %><br />

    <%= c.label :cost %> <%= c.text_field :cost, :size =>"5" %>

    <%= c.link_to_remove "Delete" %>

<% end %>

当用户在选择字段中选择产品时,我希望用 product.price 的值动态填充“成本”文本字段,但我不知道该怎么做。事实上我不知道如何获得价值然后把它...

有人可以帮帮我吗?

非常感谢。

4

1 回答 1

0

我能想到的两种方法可以做到这一点,都涉及 JS。

非 Ajax: 构建您的选项,并包含每个产品的数据属性。

<option value="<%= product.id %>" data-price="<%= product.price %>"><%= product.name %></option>

然后onchange,只需抓住选定的选项,并将它的数据价格放在成本输入字段中。

$('body').on('change', 'select.products', function(){
    var that = $(this),
      , costInput = that.parent("fieldset").("input.cost"); # Perhaps if you wrap the elements in a fieldset

    costInput.val(that.find('option:selected').val())
});

优点:有数据缺点:您必须管理表单助手附带的“选定”部分

Ajax(更好的方法): 添加一个 onchange 事件来检索所选产品的价格。

$('body').on('change', 'select.products', function(){
    var that = $(this),
      , costInput = that.parent("fieldset").("input.cost"); # Perhaps if you wrap the elements in a fieldset

     $.ajax({
        url: "products/price",
        data: {id: that.find('option:selected').val()),
        dataType: 'script'
    }).done(function ( price ) {
        costInput.val(price)
    });
});

优点:无需对 html 大惊小怪 缺点:想不出任何值得注意的地方。

于 2013-05-03T14:58:03.767 回答