views:

180

answers:

1

In Ruby on Rails I am working with an inline RJS and trying to find out which select option was selected by accessing selectedIndex property. For some reason unable to get this to work.

So, for example assigning / altering the selectedIndex property works great:

page['model_author_id'].selectedIndex = 5

But reading it and doing a comparison within the RJS doesn't work:

if page['model_author_id'].selectedIndex == 0 then xxx end

I did a debug in Firebug and it seems that RJS generates the following (incorrect) code -

$("model_author_id").selectedIndex().= = 0;

So, the question is - how can I get the values of page elements using the RJS?

+1  A: 

RJS is just a javascript generator, and the javascript does not get executed until it's client side. Therefore you cannot determine the value of the select option while still in Ruby.

If you want to do an "if" statement on the selected value you'll need to do it in Javascript.

page << "if ($('model_author_id').selectedIndex() == 0) {"
  page["model_author_id"].selectedIndex = 5 # or whatever you want here
page << "}"
ryanb
Thanks a lot for the answer ryanb, for some reason I couldn't find an answer to this in the Rails books and on forums. Actually, I think the difficulty for RJS newbie like me is that the difference is very subtle - yes, RJS is a javascript generator, but why can't it also generate conditionals / etc. for you, converting Ruby into JS?
Vlad
This is a limitation of the Ruby language. The "=" operator is a method and the behavior can be overridden, but "if" behavior cannot. If you are comfortable with javascript then I recommend not using RJS. Instead just mix javascript and erb directly (with a view file like index.js.erb).
ryanb