I am trying to make a form that adds elements to the form after certain elements have been selected. For example, After a user selects a country, I want there to be an ajax call where all of the regions/states associated with that country are found, and then inserted into a select element into the form. Then, once a user selects a region/state, the same process will take place and another element will be added to the form in reponse to the selected value. As a side note, I want to do this all unobtrusively.So far, I have this in my view:
<%= form_tag(find_school_path, :method=>'get', :class => 'form-horizontal', :id => 'find_by_country_form') do %>
<%= label_tag :country_selection, "Country" %>
<%= select_tag :country_selection, options_from_collection_for_select(@countries, :id, :name), :prompt => "Country" %>
<% end %>
Then inside of that view's javascript file I handle the ajax call upon selection of a country:
$('#country_selection').change(function(){
$.ajax({
url: "find/country_selection",
type: "GET",
data: {'country=' + $('#country_selection option:selected').value() },
})
});
Then, inside of my controller in which the above url: routes to I have:
def country_selection
@country = Country.find(params[:country])
@regions = @country.regions
respond_to do |format|
format.js { }
end
end
Lastly, in my country_selection.js.erb file I have:
$('#country_selection').after('<%= label_tag :region_selection, "State/Region" %><%= select_tag :region_selection, options_from_collection_for_select(@regions, :id, :name), :prompt => "State/Region" %>');
I have not gotten this to work. I am not even sure I am doing this the right way. When I hit select and change the option, nothing on the page changes.
SOLUTION
My code was fundamently fine, but the '.change' event was not being recognized. I change it to '.live('change', function() {...})' and it worked just fine.