Select box onchange problem

Hi,

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, c.id]},
{},
{“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?

Thnx
micheldogger

Hi Michel,

#1: just add :id => c.id to url_for, assuming c.id is the id of the
selected
option
#2: When you say, “onchange=’/some/url’” you’re not actually doing
anything. You have to assign some javascript to onchange for something
to
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
Ajax.Request
or Ajax.Updater functions.

The result will be something like:

I hope this is a helpful starting point!

Daniel

Daniel,

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, c.id]},{:id => ‘variety_select’},
{ “onchange” =>
“document.location.href=’/account/add_to_varietytmp/
#{c.id}’”}) %>

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

undefined local variable or method `c’ for
#<#Class:0x3807048:0x3807018>

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.

thnx,
micheldogger

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

Daniel,

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
    country:

<%= select(
‘country’, ‘country_id’,
Country.find_all.collect {|c| [c.name, c.id]},{},
{“onchange” =>
“document.location.href=’/controller/action/’+this.value”}
)%>

micheldogger