Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails select_tag onchange ajax request

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.

like image 498
flyingarmadillo Avatar asked Aug 14 '12 08:08

flyingarmadillo


1 Answers

It's not the tidiest code I have seen, but I see nothing wrong with it fundamentally.

I would throw some alerts in there so you can narrow down where the problem is. You could put one in the change function to make sure that is getting hit, you could add one to the country_selection.js.erb to make sure that is getting hit. This will help a bit.

I would also change the country_selection.js.erb to render a partial inside a div container where you want the new select to be, that way you can put that code into a partial and it will be a bit tidier. You can just pass a parameter to the partial that would be the selected country.

like image 84
Joel Friedlaender Avatar answered Nov 01 '22 11:11

Joel Friedlaender