2016-03-07 61 views
1

我想將從我的collection_select下拉列表中選擇的值傳遞給onchange函數。當我的名字,我的價值打印爲來源[指數],但我想這不是作爲文本本身的價值。你如何將值從collection_select傳遞給Rails中的onchange函數?

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

function updateTextArea(source){ 
var value = source; 
console.log(value); 
} 

回答

0

我認爲這將是一個例子如下:

<%= f.collection_select(:id, index.sources, :id, :name,options = {include_blank: "Please select a source..."}, html_options = {:onchange => "updateTextArea(name)"}) %> #-> f is a form tag this you use this form 

希望能幫助你

+0

如果我不使用表格?這是一個獨立的下降。 – A21

+0

好吧,試試不用'f' –

+0

這就是我在我的問題中所做的。我可以讓下拉菜單正確顯示。但是,傳遞給onchange函數的值不會打印出在下拉列表中選擇的值。 – A21

1

試試這個:

html_options = {:onchange => "updateTextArea()"} 

function updateTextArea() { 
    console.log($(this).val()); 
} 
+0

,給我以下錯誤 - 未定義的局部變量或方法'名稱' – A21

+0

請參閱我的回答的更新版本 –

+0

仍然沒有運氣 - 未捕獲TypeError:無法讀取屬性未定義的'toLowerCase' – A21

2

從 「名」 來更改參數「this.value」解決了我的問題。

<%= collection_select(:source, :index, @sources, :id, :name, options = {include_blank: "Please select a source..."}, html_options = {:onchange => "updateTextArea(this.value)"}) %> 

function updateTextArea(source){ 
var value = source; 
console.log(value); 
}