Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Ruby

Harris Kunakira
Harris Kunakira
6,157 Points

Select2 won't work with dependent form in rails

I have "select country" and "select city" forms, when user not select the country it shows "Please select country", when user selected country it will load "select city" from. It work fine. But when I try to use select2 jquery, the select2 will work with "select country" form but it will not working with "select city" form. It only load regular select form. I wonder how to make it work?

This is my code: in _form.html.erb

       <div class="field">
             <%= f.label :country %><br>
             <%= f.country_select :country, priority: %w{TH SG MY}, prompt: "Please select a country" %>
        </div>

        <div class="field">
            <%= f.label :city %><br />
            <%= render partial: 'subregion_select', locals: {parent_region: f.object.country} %>
        </div>

in _subregion_select.html.erb

      <div id="subregion-field">
           <% parent_region ||= params[:parent_region] %>
           <% country = Carmen::Country.coded(parent_region) %>
           <% if country.nil? %>
                   <em>Please select a country above</em>
           <% elsif country.subregions? %>
                   <%= subregion_select(:address, :city, parent_region) %>
           <% else %>
                   <%= text_field(:address, :city) %>
           <% end %>
     </div>

in addresses.js.coffee

      $ ->
             $("select#address_country, select#address_city").select2
                    width: '250px'

            $('select#address_country').change (event) ->
                   select_wrapper = $('#subregion-field')

                  $('select', select_wrapper).attr('disabled', true)

                  country = $(this).val()

                  url = "/addresses/subregion_options?parent_region=#{country}"
                  select_wrapper.load(url)


          $('select#locals').change (event) ->
          $(@).closest('form').submit()