.

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).

  1. # View
  2. <%= select ‘model’,'id’, Model.find(:all).map {|x| [x.name, x.id]} %>
  3. <div id=’select-b’>
  4.   <%= select ‘model’,'category_id’, Model.find(@model.id).categories.map {|x| [x.name, x.id]} %>
  5. </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.

  1. # Controller
  2. def on_model_id_change
  3.   render :update do |page|
  4.     @categories = Model.find(params[:dom_value]).categories
  5.     page.replace_html ’select-b’, :inline=>"<%= select ‘model’,'category_id’, @categories.map {|o| [o.name, o.id]} %>"
  6.   end
  7. 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.