在我的Ruby on Rails应用程序中使用jquery ajax来刷新和text_field



我的红宝石轨道应用程序是为一家建筑公司准备的,其中一部分我有两个模型,一个称为项目(rubro),另一个称为预算。创建的每个项目都有自己的价格。在我的预算表格中,我可以选择使用嵌套表格添加不同的项目及其数量。在第一列中,我有一个collection_select,它使用项目 id 选择要添加的项目,在第二列中您完成数量,在第三列中的想法是显示小计值(项目价格 * 数量)。

我的问题是,如何获取collection_select中选定的item_id,用于获取商品价格并在小计text_field中显示(商品价格*数量)?

可以做到吗?我知道我可以使用ajax和jquery来做到这一点,但我对这些很陌生。 或者有人可以给我一些其他的想法来做吗?

这是我表格的一部分,我想按照我所说的去做:_form.html.erb

<%= f.fields_for :budget_details, :wrapper => false do |form| %>
<tr class="fields ">
<td class="col-md-4">
<div class="col-md-9"><%=form.collection_select(:rubro_id, Rubro.all, :id, :name, {prompt: 'Seleccionar'}, class: 'form-control tooltip-required')%></div>
<div class="col-md-1"><%= link_to "<i class="fa fa-plus"></i>".html_safe, new_rubro_path, {:class => "btn btn-sm btn-flat bg-green ", :title => "Nuevo Rubro"} %> </div></td>
<td class="col-md-1"> </td>
<td class="col-md-2"> </td>
<td class="col-md-1"><%=form.number_field :quantity, class: 'form-control tooltip-required'%></td>
<td class="col-md-2"><%=form.number_field :subtotal, class: 'form-control', :readonly => true%></td>
<td class="col-md-1"><%=form.number_field :utility, class: 'form-control'%> </td>
<td class="col-md-1"><%=form.link_to_remove '<i class="fa fa-trash"></i>'.html_safe, class: 'btn btn-danger'%></td>
<br>
</tr>
<% end %>

我把它放在我的应用程序中.js(rubro = item)

$('#collection_select').change(function() {
var rubro = this.val();
var data = {
'rubro_id': this.val(),
}
$.ajax({
type:"GET",
url : 'rubros/rubro_price',
data : data,
success : function(response) {
var quantity = $("#rubro_quantity").val();
var price = response.price;
$("#price").val(price);
var subtotal_price = (quantity * price);
$("#subtotal_price").val(subtotal_price);
},
error: function() {
alert('Error');
}
});
});

和我的rubro_controller.rb

def rubros_price
@rubro = Rubro.find(params[:data])
end

我在这里编写伪代码,如果您在这里提供代码,那么我可以为您提供同样的帮助。

请阅读下面的每一行,如果您需要更清楚,请发表您的评论。

Select your item from the select box as you said from "collection_select".
Call the ajax for item price which you selected or you can take from your page if price presents anywhere.
You will get the price in ajax response.
Now you have "Item", "quantity" and "price"(from ajax response).
You can calculate subtotal (price * quantity) and fill text_box.

根据您的反馈,我按照上面的伪值放置 ajax 代码:

$('#collection_select').change(function() {
var item = this.val();
var data = {
'item_id': this.val();
}
$.ajax({
type:"GET",
url : "/item_price", /*Here in controller you can find price as per item id*/
data : data,
success : function(response) {
var quantity = $("#item_quantity").val();
var price = response.price;
var subtotal_price = (quantity * price);
$("#subtotal_price").val(subtotal_price);
},
error: function() {
alert('Error occured');
}
});
});

最新更新