Search code examples
javascriptruby-on-railsujs

Rails Updating Contents of a Form When a Select Element Changes


I have a form with a select box and three text input boxes. When the option in the select box changes, I want to update the three text input boxes with values corresponding to the selected option. The values are a model object stored on the server.

I'm using Rails 3 and trying to keep things unobstrusive, but I can't find a clean way to do this. I've come up with a couple horrendous, messy solutions, but nothing clean yet. What would be a good way to tie this all together? In particular, I am having trouble with the select element requesting the model object from the server.

Here's the view that generates the form:

= form.select :region_id, region_options_for_select(@business_location.region), :prompt => '-- Region --'
= form.text_field :city
= form.text_field :state, :label => 'Province/State'
= form.text_field :country

So I wish to populate the city/state/country fields whenever "region" is changed. Note that region is also part of the form itself.


Solution

  • In jQuery, something like this could work:

    $("select").live("change", function(e) {
      e.preventDefault();
      $.ajax({
        url: "/location/" + $(this).val(), //I think, it could be something else
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        success: function(data) {
          //you're returning a JSON object, so just iterate through it and bind it to
          //the value attributes of each field
        },
        error: function(xhr,exception,status) {
          //catch any errors here
        }
      });
    });
    

    On the Rails side, in the LocationsController#show:

    @location = Location.find(params[:id])
    respond_to do |format|
      format.json { render :json => @location.to_json, :status => 200 }
    end
    

    That's roughly how it could work. Substitute whatever the controller/model names you have for the ones I made up.