[LRUG] [RoR] Problem observing multiple fields

Richard Livsey richard at livsey.org
Tue Sep 22 05:59:06 PDT 2009


Jordi,

Personally I don't use the built in Rails JS helpers in order to avoid
having JS written directly to the page.
Writing the JS manually in a separate file makes it easier to control
and I find it nicer (both in output and for maintenance) to keep the
logic separate from the HTML.

Here's how I might do it in plain JS (assuming prototype) to update
some other div based on the result of an ajax request each time a
selectbox with a class of 'changer' is changed.

(See http://gist.github.com/191044 for a formatted version)

document.observe('dom:loaded', function(){
  $$('select.changer').each(function(select){
    select.observe('change', function(){
      new Ajax.Updater('other_div', '/some/action', {
        parameters: {selected: $F(select)}
      });
    });
  });
});

If you're using RJS, you could replace the Ajax.Updater with a normal
Ajax.Request.

It would need modifying to submit to a different URL based on the
selectbox, or pass another parameter for the name of the selectbox
depending on your needs.

You still need a different ID for each selectbox, but you could write
a helper to output this instead of being in the view directly.

Then you could have the following to clean that part up:

<%= collection_select_for_item(item) %>

Hope that helps.

-- 
Richard Livsey
Minutebase - Online Meeting Minutes
http://minutebase.com
http://livsey.org



On Tue, Sep 22, 2009 at 2:26 PM, Jordi Noguera Leon
<jordinoguera83 at gmail.com> wrote:
> Hi all!!
>
> I've got the following problem: I have a collection of items, each of one
> having a drop down list, for a given field. I'd like to trigger an action
> every time a selection is done in any of the lists. This is what I've done
> (more or less...):
>
> <% @items.each do |item| %>
> <%= collection_select(:subitem, :id, item.find.whatever, :id, :description)
> % >
> <%= observe_field :subitem_id, :url => { :action => 'some_action' }, :with
> => :subitem_id %>
> <% end %>
>
> I'd say, at some point it worked, but now it only works for the first item.
> For the other items, no action is triggered... So, I thought that maybe the
> problem was that all the fields had the same name. And then, I've tried it
> putting a different name to each one:
>
> <% @items.each do |item| %>
> <%= collection_select('subitem' + item.id.to_s, 'id', item.find.whatever,
> :id, :description) % >
> <%= observe_field 'subitem' + item.id.to_s + '_id', :url => { :action =>
> 'some_action' }, :with => :subitem_id %>
> <% end %>
>
> This thing works fine, but I think it's quite ugly... Does anyone know of a
> better solution?
>
> Thanks!
> Jordi



More information about the Chat mailing list