2012-10-17 41 views
1

我正在學習軌道上的紅寶石。在我的項目 中,我使用了collection_select。我的代碼是collection_select onchange事件和選定的紅寶石軌道上

<%= collection_select(:sport_name,count,Sport.find(:all, :order => 'id'), :id, :sport_name, {} , 
    {:selected  => ps.sport.id, 
    :include_blank => "Select Sport", 
    :onchange  => "hidvalue("+ps.sport.id.to_s+","+count.to_s+")", 
    :style   => "margin:1px 0 0;width:210px;" }) %> 

onchange作品 - selected不起作用

如果我不是做

<%= collection_select(:sport_name,count,Sport.find(:all, :order => 'id'),:id, :sport_name, 
    {:selected  => ps.sport.id, 
    :include_blank => "Select Sport", 
    :onchange  => "hidvalue("+ps.sport.id.to_s+","+count.to_s+")" }, 
    {:style   => "margin:1px 0 0;width:210px;" }) %> 

onchange不起作用,但selected作品。我想一起使用onchangeselected。這段代碼有什麼問題?

+0

你的onchange函數應該做什麼? –

+0

用於將選定值保存到隱藏字段。 – tinzawtun

回答

5

好吧,「selected」是一個選項,但是「onchange」是一個HTML屬性,您想要分配給生成的HTML。這兩種不同類型的東西是假定被傳遞到不同參數內的collection_select。

特別是,「selected」應該作爲第五個(「options」)散列中的鍵/值對傳入,而「onchange」應作爲第六個(「html_options」)散列的一部分傳入。

查看http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#method-i-collection_select瞭解更多信息

+1

感謝Bob!我像這樣改變我的代碼。這行得通! \t <%= collection_select(:sport_name,count,Sport.find(:all,:order =>'id'),:id,:sport_name,options = {:include_blank =>「Select Sport」,:selected => ps .sport.id},html_options = {:onchange =>「hidvalue(」+ ps.sport.id.to_s +「,」+ count.to_s +「)」,:style =>「margin:1px 0 0; width:210px ;「})%> – tinzawtun