I am learning ruby on rails. In my project
I use collection_select. My code is
<%= 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 works – selected doesn’t work
If I instead do
<%= 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 doesn’t work, but selected works. I want to use onchange and selected together. What is wrong with this code?
Well, “selected” is an option, but “onchange” is an HTML attribute that you want to assign to the generated HTML. Those two different types of things are supposed to be passed in to collection_select inside different arguments.
In particular, “selected” should be passed in as key/value pair in the fifth (“options”) hash, while “onchange” should be passed in as part of the sixth (“html_options”) hash.
See http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#method-i-collection_select for more information