我正在尝试以下操作。 主窗体中的客户选择选项。当用户在主窗体中选择客户时,他的账单应出现在所有后续部分中。
我正在使用 ryan bates 的nested_form gem 来获取部分内容。代码如下。
<%= simple_nested_form_for @money_receipt do |f| %>
<div class="customers"><%= f.collection_select :customer_id, Customer.all, :id, :name, options ={:prompt => "-Select a Customer"}, :style=>'width:210px;'%></div><br />
/*rest of the code*/
<%= f.link_to_add "Add line items", :money_receipt_line_items %>
在部分内
<div class="bill">
<%= f.collection_select :customer_bill_id, CustomerBill.all,:id,:id, {:prompt => "Select Customer bill"}, :style => 'width:202px;' %></div><br />
/*rest of the code*/
上面的jQuery代码如下
jQuery(document).ready(function(){
jQuery(".customers select").bind("change", function() {
var data = {
customer_id: jQuery(this).val()
}
jQuery.getJSON(
"/money_receipts/get_bills",
data, function(data){
var result = "",a,x;
var b = "<option>Select customer Bill</option>"
for(i=0;i<data.length; i++)
{
a = data[i];
result = result + "<option value="+a[0]+">"+a[0]+"</option>";
console.log(result);
}
child=jQuery('.bill select').html(b+result);
});
});
});
最后在我的 Controller 中。 def get_bills
@bill_amount = CustomerBill.find_all_by_customer_id(params[:customer_id]).map{|bill| [bill.id]} if params[:customer_id]
respond_to do |format|
format.json { render json: @bill_amount }
end
end
我试图过滤账单并放入 div id bill
。现在,如果我在 jQuery 代码中执行 console.log
,我将获得 customer_id 和账单,但我无法发布它。如果我在 child
上执行 console.log
,我会得到这样的输出 jQuery()
。我哪里出错了?有没有更好的方法来实现上述目标?需要指导。提前致谢。
最佳答案
我个人更喜欢将 HTML 放入局部的方式,而不是用 JS 代码绘制。
像这样:
money_receipt.js:
$('.customers select').change(function(){
$.getScript('/money_receipts/get_bills?customer_id='+$(this).val())
})
get_bills.js.erb:
$('.bill select').html('<%=j render 'get_bills'%>')
_get_bills.html.erb:
<% @bills.each do |bill| %>
<option value="<%=bill.id%>"><%=bill.title%></option>
<% end %>
代码行数越少,出现错误的地方就越少。
关于jquery - jQuery 对 ruby on Rails 中的部分数据执行的默认操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13853248/