Dependent Dropdown Contents with jquery-select2

限于喜欢 提交于 2020-01-03 17:06:33

问题


I have a Rails 4 app where I'm using Jquery-select2 for my dropdown lists. I have two dropdowns where I want the selection in the first do dictate what the user can select in the second. Sort of like selecting a country and being given a list of states for that country.

In my application I have Demographic and Response models. When someone selects a Demographic I want to populate the Responses list with the appropriate items for that Demographic.

I had this working before I started using Select2. But, I'm missing some of the nuances in how to get it working with Select2. I'm so so with Rails but Javascript and Jquery are my weak points.

Here is my form:

<form>
      <%= f.label :demographic %><br>
      <%= select_tag "demographics", options_from_collection_for_select(@demographic, "id", "demographic_name"), id: "simple-example" %></br></br>
      <%= f.label :operator %><br>
      <%= select_tag "operators", options_from_collection_for_select(@operator, "id", "name"), id: "operator" %></br></br>
      <%= f.label :response %><br>
      <%= select_tag "responses", options_from_collection_for_select(@response, "id", "name"), id: "response" %></br></br>
      <%= f.label :operator_selection %><br>
      <%= select_tag "operator_selections", options_from_collection_for_select(@operator_selection, "id", "name"), id: "operator_selection" %></br></br>
    </form>

Here is some CoffeeScript which I found and modified and had working prior to Select2:

jQuery ->
  responses = $('#query_response_id').html()
  $('#query_demographic_id').change ->
    demographic = $('#query_demographic_id :selected').text()
    escaped_demographic = demographic.replace(/([ #;&,.+*~\':"!^$[\]()=>|\/@])/g, '\\$1')
    options = $(responses).filter("optgroup[label='#{escaped_demographic}']").html()
    if options
      $('#query_response_id').html(options)
      $('#query_response_id').parent().show()
    else
      $('#query_response_id').empty()
      $('#query_response_id').parent().hide()

The line of code I used before Select2 for the Response model dropdown was:

<%= f.grouped_collection_select :response_id, Demographic.order(:demographic_name), :responses, :demographic_name, :id, :name, include_blank: :true %>

When I look at that it appears that somehow I need to move :responses, :demographic_name, into this line:

<%= select_tag "responses", options_from_collection_for_select(@response, "id", "name"), id: "response" %>

But, everything I've tried has failed. I've looked at this and this and this, but none of them are Rails related so I'm stuck.

Any ideas?

All help is greatly appreciated.


回答1:


Start with the simplest case: First of all, just get the form working without Select2 or Chosen, or whatever. Just use basic Select drop downs, so you can see what's happening.

In your situation, you can load all the Demographics up, and create an empty select for the Responses:

<%= form_tag("/test") do |f| %>
  <%= select_tag "demographic", options_from_collection_for_select(@demographic, "id", "name"), id: "demographic", class: "chosen" %><br>
  <%= select_tag "responses", "", id: "responses", class: "chosen" %>
<% end %>

Then when the selected Demographic changes, you can update the options for the Responses over ajax:

$(document).ready(function() {

  // Listen for the demographic changing
  $('#demographic').change(function(){

    // Grab the id of currenly selected demographic
    var demographic_id = $(this).val();

    // Query the responses for this demographic:
    $.get( "/responses.json", { demographic_id: demographic_id }, function( data ) {

      // Remove the existing options in the responses drop down:
      $("#responses").html("");

      // Loop over the json and populate the Responses options:
      $.each( data, function( index, value ) {
        $("#responses").append( "<option value='" + value.id + "'>" + value.name + "</option>" );
      });

    });
  });

});

Finally, you'll just need an index action on the ResponsesController to give you the json for the select box. You need JSON in the following format.

[{"id":2,"name":"Direct Request - Telecommunication"},{"id":3,"name":"Direct Request - Internet/Electronic"},{"id":4,"name":"Company Request - Written"}]

This action should give you something like it:

class ResponsesController < ApplicationController

  def index
    @responses = Response.order(:name)
    @responses = @responses.where(demographic_id: params[:demographic_id]) if params[:demographic_id].present?

    # You don't need this respond to block if you have a jbuilder view set up at app/views/responses/index.json.jbuilder
    respond_to do |format|
      format.json { render json: @responses }
    end
  end

end

Now when your Demographic changes in the first select, you should get a filtered list of Responses in the second select. If this is working, you can now add the JQuery plugin of your choice. Personally, I prefer Chosen to Select2.

To get chosen working in the above case, you just need to modify the Javascript slightly:

$(document).ready(function() {

  // Attach the chosen behaviour to all selects with a class of "chosen"
  $('.chosen').chosen();

  $('#demographic').change(function(){
    var selected_demographic = $(this).val();

    // Query the responses for this demographic:
    $.get( "/responses.json", { demographic_id: selected_demographic }, function( data ) {

      // Remove the existing options in the responses drop down:
      $("#responses").html("");

      // Loop over the new response json and populate the select list:
      $.each( data, function( index, value ) {
        $("#responses").append( "<option value='" + value.id + "'>" + value.name + "</option>" );
      });

      // Now reset chosen, with the new options:
      $("#responses").trigger("chosen:updated");
    });
  });

});



回答2:


I don't know rails, but i used Javasctipt/Jquery, Bootstrap.

Is this solve your problem.

I binding country and state values from Javascript Array.

Demo: http://jsfiddle.net/4ad7A/316/

    <script>
   $("#country, #state").select2();populateCountries("country", "state");
   </script>


来源:https://stackoverflow.com/questions/33617331/dependent-dropdown-contents-with-jquery-select2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!