0
votes

I have a simple doubt. I've two drop down fields one for states and other for cities. Im loading these two from my database where I have two tables with name states and cities. Also when I select one state cities are changed acordingly as I have written a jquery code too.. This is how I load all states into my select tag

<%= jl.select :state_id , State.all.map{|j| [j[:name], j[:id]]}, {class: 'select2'} %>        

What I want is when I load that page intialy I dont want my cities field to be blank. I want it to be a dropdown list full of cities corresponding to some particular state_id. So how should my select tag for cities should Look. City table contains name,id and state_id.

2
Get all the cities of your first state and then set into the drop down.But better way to do it through ajax. - Bharat soni

2 Answers

4
votes

Add id to your states dropdown

<%= jl.select :state_id , State.all.map{|j| [j[:name], j[:id]]}, {class: 'select2',id:'states_dropdown'} %>  

Then your Cities dropdown should look as the following:

<%= jl.select :city_id , City.where(:state_id=> "specific_id").map{|j| [j[:name], j[:id]]}, {class: 'select2'} %> 

and add this in your coffee script file

$("#states_dropdown").change ->
        $.ajax
            url: '/category/childrens'
            type: 'GET'
            data : 
                state_id: $(this).val()
            success: (data, status, response) ->
                #update cities dropdown
            error: ->
                # Hard error
2
votes

you should write code on load.

var cities_obj_arr = <%= @cities.to_json %>;

$(document).on('change', "#state_select_box", function(){
  var state_id = $(this).val();
  var str_option = '';
  $.each(cities_obj_arr, function(index, city_obj){
     if(state_id == city_obj['city']['state_id']){
       str_option = str_option + "<option value='"+city_obj['city']['name']+"'">"+city_obj['city']['name']+"</option>"; /*city_obj['city']['name'] city is object name for cities*/
     }
  });
  $(this).html(str_opotion);
});

please have a look on image, it will help more.

enter image description here