2012-08-07 76 views
1

你好傢伙我試圖嘗試在這裏動態選擇。只要我選擇了客戶,賬單中的總價值就會到達並顯示在文本字段標籤中。動態顯示文本字段中的數據ruby on rails

視圖

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局部

<% 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的方式,所以任何人都可以指導我如何獲得文本字段中的值?預先感謝。

回答

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的。再培訓局的部分,你可以簡單地有

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

一切順利:)

2

據我所知,total_value文本字段不顯示任何內容。你可以嘗試輸出選項的值,並檢查它是否總是有值?我建議你查看text_field_tag的文檔。基本上,它接受這樣的三個變量:

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

是啊,我understood..thanks .. :)但現在我不知道如何把總價值在文本字段標籤...!我該怎麼做??? – deeraj 2012-08-08 05:18:18

+0

你的意思是將它設置爲文本字段的默認值?不設置值屬性的工作? – maru 2012-08-09 13:41:34

+0

我試着設置值爲@ cust_bill.total_value,但它似乎不工作。 – deeraj 2012-08-10 03:53:38

相關問題