在rails上的文本字段ruby中动态显示数据

时间:2012-08-07 05:47:13

标签: javascript ruby-on-rails ruby-on-rails-3 controller

大家好我想在这里尝试动态选择。一旦我选择了客户,他的账单中的总价值就会显示在文本字段标签中。

观点     

  jQuery(document).ready(function(){
   jQuery(".customerid").bind("change", function() { 

      var data = {
        customer_id: jQuery(".customerid :selected").val()  
      }
      jQuery.ajax({
        url: "get_cust_bill",
        type: 'GET',
        dataType: 'script',
        data: data
      });
    });
  });
</script>


 <div class ="customerid"><%= f.label :customer_id %>
    <%= f.collection_select :customer_id, Customer.all, :id, :name, options ={:prompt => "-Select a Customer"}, :class => "state", :style=>'width:210px;'%></div><br />

     <div class ="customerbill">
      <%= f.label :total_value, "Total Value" %>
  <%= render :partial => "customerbill" %>

js.erb文件

jQuery('.customerbill').html("<%= escape_javascript(render :partial => 'customerbill') %>");

customerbill partial

<% options = []
  options = @cust_bill.total_value if @cust_bill.present? %>
<%= text_field_tag "total_value", options %>

在控制器中

def get_cust_bill
    @cust_bill = CustomerBill.find_all_by_customer_id(params[:customer_id]) if params[:customer_id]
  end

我觉得问题在于部分,我调用options的方式所以任何人都可以指导我如何获取文本字段中的值???提前谢谢。

2 个答案:

答案 0 :(得分:2)

根据我的理解,total_value文本字段不显示任何内容。您可以尝试输出选项的值并检查它是否总是有值?我建议您查看text_field_tag的文档。基本上,它接受三个这样的变量:

text_field_tag(name, value = nil, options = {})

答案 1 :(得分:1)

我使用的是getJSON方法....我觉得可以在这里使用。希望以后的工作。

jQuery(document).ready(function()
    {
    jQuery(".customerid select").bind("change", function() {
          var data = {
            product_id: jQuery(this).val()  
          }
          jQuery.getJSON(
             "/controller_name/get_cust_bill",
            data,
            function(data){
          var result = "";
          res = parseFloat(a[1]);
           jQuery('.price input').val(res);
          });            
            });
        });

控制器

def get_cust_bill
    @cust_bill = CustomerBill.find_all_by_customer_id(params[:customer_id]).map{|p| [p.price]} if params[:customer_id]
respond_to do |format|
      format.json { render json: @cust_bill }
    end
  end

所以不需要调用js。 erb partial你可以简单地拥有

<div class = "price"><%= f.input :price, :label => 'Price', :input_html => { :size => 20} %></div><br/>

一切顺利:)