Friday, February 4, 2011

How to dynamically update form elements in Rails using Ajax


Here’s the situation: You have two SELECT elements on a form. When the user chooses an item out of the first SELECT element, the contents of the second SELECT element need to change and show different values based on the initial selection.
This used to take quite a bit of JavaScript wizardry. But it’s pretty straightforward in Rails using a bit of Ajax. Here’s how:
First, make sure you’re including the Ajax libraries (Prototype, script.aculo.us, etc.) in your layout like so:
       <%= javascript_include_tag :defaults %>


...
Next, create a form with your initial SELECT, and empty second SELECT, and set up field observer. Here’s a really simple example:




<%= observe_field "states", :update => "cities",
:with => "city_id", :url => { :controller => "test",
:action => "get_cities" } %>






Finally, you’ll need to set up a method to handle the call from the observer and a corresponding view page to generate the HTML content that will replace everything betwen the SELECT tags in the second SELECT. Here’s an example "get_cities" controller:
def get_cities
@cities = City.find_by_state(:all)
end
And an example "get_cities.rhtml" file:
<% for city in @cities %>

<% end %>
And there you go. This much should dynamically update the "cities" SELECT element with new content every time the "onchange" event is fired on the initial "states" SELECT form element.

No comments:

Post a Comment