July 7, 2006
Updating ’select’ controls with AJAX
In web design there are frequently times when a form needs to be able to have the contents of ’select control B’ depend on the contents of ’select control A’ (or some other control type for that matter). Using conventional web design methods, one would have to define a ‘onChange’ javascript event for ’select control A’, which fires off a callback that updates the second select control.
This is cumbersome to code, and it leads to upleasant page refreshes every time the user changes the value of ’select control A’.
Another way to handle this is by using AJAX methods to update the second control as needed. This is fairly easy in Rails, and is even easier if you make use of the KRJS plugin (http://www.agilewebdevelopment.com/plugins/krjs).
-
# View
-
<%= select ‘model’,'id’, Model.find(:all).map {|x| [x.name, x.id]} %>
-
<div id=’select-b’>
-
<%= select ‘model’,'category_id’, Model.find(@model.id).categories.map {|x| [x.name, x.id]} %>
-
</div>
In this example, the second select (’select-b’) is normally populated with ‘categories’ associated with the initially selected model. Changing the model would not normally update the second select, so things would be all wrong.
-
# Controller
-
def on_model_id_change
-
render :update do |page|
-
@categories = Model.find(params[:dom_value]).categories
-
page.replace_html ’select-b’, :inline=>"<%= select ‘model’,'category_id’, @categories.map {|o| [o.name, o.id]} %>"
-
end
-
end
This is probably the easiest way to update a select box using AJAX. Remember, this only works with the KRJS plugin.
UPDATE: Of course all of this only works if you have AJAX enabled by adding <%= javascript_include_tag :defaults %> in the
of your layout file.
Filed by Kevin Olbrich at 12:27 pm under Ruby on Rails, User Interface, select controls
36 Comments