0

I have a form that allows the user to choose a country. Depending on which country is selected, I need to change the State/Province drop-down to include either a list of states or a list of provinces. I was going about this using the observe_field tag, but that was depreciated in rails 3...

So.., how should one go about this now? I am using select_tag to populate the drop-downs, and the arrays used in the options_for_select are all stored server-side and made accessible in the controller action, so I can't access them from javascript..

1 Answer 1

4

Using the Carmen gem: https://github.com/jim/carmen.

I did the following some times ago (AJAX).

HTML:

    <p>
        <label>Country <span>*</span></label>
        <%= profile_form.select(:country,Carmen.countries, {:include_blank => 'Select a Country'}, :id => "profile_country") %>
    </p>
    <p>
        <label>State <span>*</span></label>
        <%= profile_form.select(:state,  "" , {:include_blank => 'Select a Country first'}, :id => "profile_state") %>
    </p>

Controller:

def states
  begin
    render :json => Carmen::states(CGI::unescape(params[:country]))
  rescue 
    render :json => {"content" => "None"}.to_json
  end
end 

Javascript with jQuery:

$('#profile_country').change(function() {
    if ($(this).val() == '')
    {
      $('#profile_state').empty();
      $('#profile_state').append( $('<option>No state provided for your country</option>'));
    }
    else {
        $.ajax({
            type: "GET",
            url: "/remote/get_states/" + encodeURIComponent($(this).attr('value')),
            success: function(data){
                if (data.content == 'None')
                {
                    $('#profile_state').empty();
                  $('#profile_state').append( $('<option>No state provided for your country</option>'));
                }
                //handle the case where no state related to country selected
              else
             {
                $('#profile_state').empty();
                $('#profile_state').append( $('<option>Select your State</option>'));
                jQuery.each(data,function(i, v) {
                 $('#profile_state').append( $('<option value="'+ data[i][1] +'">'+data[i][0] +'</option>'));
            });
        }
        }
      });
    }
 });
Sign up to request clarification or add additional context in comments.

1 Comment

To the users who maybe wondering why the above code is not working, please add the js in $(document).ready(function (){......}); block

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.