tinzawtun
tinzawtun

Reputation: 35

collection_select onchange event and selected ruby on rails

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?

Upvotes: 2

Views: 7028

Answers (1)

Bob Gilmore
Bob Gilmore

Reputation: 13788

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

Upvotes: 5

Related Questions