Select box onchange problem



i’ve got the following problem. I have a check_box witch shows
a list of varieties. Now i want to call a action when the user
changes his selection. (the method to be called, will store the
selection from the user).

This is my code:

<%= select(‘variety’, ‘variety_id’,
Variety.find_all.collect {|c| [c.description,]},
{“onchange” =>
url_for(:controller => ‘account’,
:action => ‘add_to_varietytmp’)} ) %>

HTML output:

Two questions:

1… I need to give a id to the method ‘add_to_varietytmp’, how do
I give the correct id from the selected option?

2… When I select an option in my selectbox, onchange, the method
‘add_to_varietytmp’ doesn’t run. So how do I get my onchange
to work?



Hi Michel,

#1: just add :id => to url_for, assuming is the id of the
#2: When you say, “onchange=’/some/url’” you’re not actually doing
anything. You have to assign some javascript to onchange for something
happen. In this case I’m not sure how to use Rails to generate the
javascript for you, but you’re going to want to use Prototype’s
or Ajax.Updater functions.

The result will be something like:

I hope this is a helpful starting point!




i’ve been looking for it. I found a quick 'n dirty solution
but i keep struggling with the id to pass to my action.

This is the solution I found:

<%= select(‘variety’, ‘variety_id’, Variety.find_all.collect {|c|
[c.description,]},{:id => ‘variety_select’},
{ “onchange” =>
#{}’”}) %>

I tried to pass the id with, but that doesn’t work. (look above)
I get the following error:

undefined local variable or method `c’ for

First I’ll need a quick solution, even if it isn’t that nice.
My problem now is how to get the value from the selected option.



I didn’t catch this earlier, but part of the problem is that when you
use, it’s out of scope. Try
“document.location.href=’/account/add_to_varitetytmp/’+this.value” ,
will use javascript to set the id part of the path based on the option



Thank you. IT WORKS!!!

So for everybody who might want to use this in the future:

  • Table: Countries
    id integer
    name varchar(45)

  • Below, the code for a select menu in a view, wich shows all the
    countries and if you select a country, the onchange action will
    call a controller and action together with the id of the selected

<%= select(
‘country’, ‘country_id’,
Country.find_all.collect {|c| [,]},{},
{“onchange” =>