I would like to populate options for collection_select based on previous collection_select selection. I have in one selection Sports and I would like to populate next selection with teams based on that sport.
Problem is that all examples that I found are for older versions of ROR, so I decided to ask here. I know i have to add some nasty things like :
html_options = {:onchange=>'d=$("#player_sports_id").val();$.ajax({type: "GET", url: "/players/returnsel1.js?sports_id="+d, dataType: "script" });'})
to call player#returnsel1 and get returned returnsel1.js.erb.
In returnsel1 I have variable
@teamstoreturn=Teams.where(:sport_id=params[:sport_id])
So how should jquery returnsel1.js.erb looks like?
Thank you.
Dorijan
edit1:
here is how it actually looks, but it does not work:
html_options = {:onchange=>'d=$("#player_sports_id").val();$.ajax({type: "GET", url: "/players/returnsel1?sports_id="+d, dataType: "script",success: function(data){ $("#player_teams_id").html(data)} });'})
and in controller it is like this:
def returnsel1
@teamstoreturn=Team.where(:sports_id=>params[:sports_id])
render :inline => "<%= collection_select(:player, :teams_id, @teamstoreturn, :id, :naziv) %>"
end
if I go to /players/returnsel1?sports_id=2 I got correct drop down menu
what have I done wrong?
edit2:
there should be dataType: “html” instead dataType: “script”
and now it is working 🙂
You should extend the .ajax request with a function, which can handle the successful answer. Without this, the answer is discarder. Propably this function should contain a jquery code, to change the other selections content.
This way you change this element, so you must render this as a html fragment, which must be inserted. So no javascript code in the answer is required, only html. E.g.: