2016-02-29 59 views
0

我有以下的選擇下拉在我的軌道。我正在關注從API(http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#method-i-collection_select)的語法:如何將onchange動作添加到collection_select?

collection_select(對象,方法,收集,value_method,text_method,選項= {},html_options = {})

<%= collection_select(:sources, :source_id, Source.all, :id, :name, :include_blank => "Please select a source...", html_options = {:onchange => "updateTextArea()"}) %> 

function updateTextArea(){ 
alert('source changed') 
} 

我能夠在不包含html_options的情況下,使用下拉列表可以很好地顯示來自數據庫的值。但是,我堅持試圖讓onchange動作發生。

回答

0

我認爲選項需要在散列表中(當前有include_blank的部分)。嘗試改變這種

<%= collection_select(:sources, :source_id, Source.all, :id, :name, :include_blank => "Please select a source...", html_options = {:onchange => "updateTextArea()"}) %> 

這個

<%= collection_select(:sources, :source_id, Source.all, :id, :name, options = {include_blank: "Please select a source..."}, html_options = {:onchange => "updateTextArea()"}) %> 
+0

這讓我過去的語法異常,但它並沒有給我一個警告的對話,所以我不知道爲什麼功能當我更改下拉值時未觸發。 – A21

+0

我的錯誤,我的

0

我認爲,在地方的options =html_options =你需要通過實際的哈希值本身(如你實際上include_blank => true一樣)。我只會用花括號將這些散列明確標記以區分它們:

<%= collection_select(:sources, :source_id, Source.all, :id, :name, { :include_blank => "Please select a source..."}, {:onchange => "updateTextArea()"}) %> 

希望這有助於。

編輯:

我忘了補充一點,如果updateTextArea() JS功能沒有綁定到一個窗口,則可能是拿起它的一個問題(我有過類似的問題)。爲了安全我還要做(如果你不使用CoffeScript):

window.updateTextArea = function() { /* Your code */ } 
相關問題