18th Jul 2007

How-to: Pop-up Menu Selection AJAX in Rails

The problem: In Rails, how do you create a popup menu that calls a given action (to replace a div or whatever else) and passes the selected option as an argument when a new selection is made?

This took me way longer than I thought it would to figure out how to do, so I’m posting the answer here as well for anyone trying to do the same thing.


< %= select_tag :person_choice, options_for_select(@persons),
:onchange => remote_function(:update => “divToBeUpdated”, :with => ‘Form.Element.serialize(this)’, :url => { :action => ‘update_person’}) %>

The key here is the :with => ‘Form.Element.serialize(this)’ option. It’s a bit of magic javascript that passes the selected object along with AJAX call, but I actually don’t really understand it much beyond that. If anyone wants to give me a more thorough explanation, it would be highly appreciated.

Huzzah!
Update: Props to OnRails.org.

One Response to “How-to: Pop-up Menu Selection AJAX in Rails”

  1. Jon Says:

    how do you get at the selected object in the controller please?

Leave a Reply