AlexRor
AlexRor

Reputation: 51

Select onchange with city-state ruby gem

I'm trying to use city-state gem (https://github.com/loureirorg/city-state) and make selector of cities dynamically updatable with Javascript depends on state selector.

My idea: After select state, "form.select :city" will be populate cities only for this state.

Here is my ...html.erb

<%= fs.select :state_code, options_for_select(us_states), {}, class: "form-control", id: "state_code", :onchange => "javascript: state_code();"  %>

<%= fs.select :city, options_for_select(CS.get :"#city", :al), {},   class: "form-control", id: "city" %>

Here is my Javascript:

   <script type="text/javascript">
     $("#state_code").onchange( function() {
      $("#city").val("state_code").change();
 })
</script>

Upvotes: 0

Views: 1436

Answers (1)

Mashhood
Mashhood

Reputation: 403

You need to modify your HTML population and JS code. Also, an action in Application Controller to respond to the request to fetch the cities of that state.

---
JS
---
$(document).on('change', '#states-of-country', function(e) {
  var cities_of_state, input_state, state;
  input_state = $(this);
  cities_of_state = $('#cities-of-state');
  state = this.options[e.target.selectedIndex].id;
  if (state === 'no-state') {
    return cities_of_state.html('');
  } else {
    $.ajax({
      url: '/cities/' + $(this).children(':selected').attr('id'),
      success: function(data) {
        var opt;
        opt = '<option value="" selected>Select Your City</option>';
        if (data.length === 0) {

        } else {
          data.forEach(function(i) {
            opt += '<option value="' + i + '">' + i + '</option>';
          });
          cities_of_state.html(opt);
        }
      }
    });
  }
});
------------------------
Application Controller:
------------------------

def cities
  render json: CS.cities(params[:state], :us).to_json
end

-----------
routes.rb:
-----------
get 'cities/:state', to: 'application#cities'
-----
HTML
-----
<select id="states-of-country" name="project[state]">
  <option id="no-state" value="" selected>Select Your State</option>
  
  /* For states within US */
  <% CS.states(:us).each do |key, value| %>
    <option value="<%= value %>" id="<%= key %>"><%= value %></option>
  <% end %>
</select>
      
<select id="cities-of-state" name="project[city]" class="form-control form-control-small" required>
  <option value="" selected>Select Your City</option>
</select>
            
            
            
            

So, when the value is changed, a GET request will be made to server. Then upon looking the state code, it will return a list of cities which belong to that particular state. On AJAX success, these cities are being populated.

Upvotes: 1

Related Questions