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:

<html>
<head>
       <%= javascript_include_tag :defaults %>
</head>
<body>
...

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

<form>

<select id="states" name="states">
    <option value="0"></option>
    <option value="1">Colorado</option>
    <option value="2">Illinois</option>
    <option value="3">Wyoming</option>
</select>

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

<br />

<select id="cities" name="cities">
    <option></option>
</select>

</form>

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 %>
    <option value="<%= city.id %>"><%= city.name %></option>
<% 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.


Posted: April 12th, 2007 by Neal Enssle
Tags: , , , ,
25 Comments »


Leave a Reply

essay writer | essay online | write my essay for me