2013-05-03 75 views
0

我有一个“卖”的形式,我使用fields_for把有关产品的信息出售。动态字段field_for

这里是我的fields_for形式:

我想有动态充满product.price价值的“成本” text_field当用户在选择区域选择的产品,但我不不知道该怎么做。事实上,我不知道如何获得价值,然后把它...

任何人都可以帮助我吗?

非常感谢。

+0

从表单中获取成本听起来像一个非常糟糕的主意。在另一端显示给客户可能很有用,但最好不要使用输入。 – giorgian 2013-05-03 14:24:58

+0

事实上,它只是用来获取信息,它不是为了顾客,而是为了卖家。 – eluus 2013-05-03 14:32:02

+0

让我知道下面的答案是否可以解决您的问题。 – omarvelous 2013-05-09 17:12:46

回答

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()) 
}); 

优点:数据是有 缺点:你将不得不管理自带的形式佣工“选择的”部位

阿贾克斯(更好的方法): 添加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 缺点大惊小怪:想不出什么值得一提的。