jquery-select2 的相关下拉内容

Dependent Dropdown Contents with jquery-select2

我有一个 Rails 4 应用程序,我在其中使用 Jquery-select2 作为我的下拉列表。我有两个下拉菜单,我希望第一个中的 selection 指示用户可以在第二个中 select 做什么。有点像 select访问一个国家并获得该国家/地区的州列表。

在我的应用程序中,我有人口统计模型和响应模型。当某人 select 是人口统计时,我想用适合该人口统计的项目填充响应列表。

在我开始使用 Select2 之前,我已经完成了这项工作。但是,我遗漏了一些关于如何让它与 Select2 一起工作的细微差别。我对 Rails 非常满意,但 Javascript 和 Jquery 是我的弱点。

这是我的表格:

<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>

这是我发现并修改并在 Select2 之前工作的一些 CoffeeScript:

jQuery ->
  responses = $('#query_response_id').html()
  $('#query_demographic_id').change ->
    demographic = $('#query_demographic_id :selected').text()
    escaped_demographic = demographic.replace(/([ #;&,.+*~\':"!^$[\]()=>|\/@])/g, '\')
    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()

我在 Select2 之前为响应模型下拉列表使用的代码行是:

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

当我看到它时,我似乎需要将 :responses, :demographic_name, 移动到这一行:

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

但是,我尝试的一切都失败了。我看过 and this and ,但其中 none 与 Rails 相关,所以我被卡住了。

有什么想法吗?

非常感谢所有帮助。

我不知道rails, 但是我用了 Javasctipt/Jquery, Bootstrap.

这是否解决了您的问题。

我绑定来自 Javascript 数组的国家和州值。

演示:http://jsfiddle.net/4ad7A/316/

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

从最简单的情况开始:首先,让表单在没有 Select2 或 Chosen 或其他任何东西的情况下工作。只需使用基本的 Select 下拉菜单,这样您就可以看到发生了什么。

根据您的情况,您可以加载所有人口统计数据,并为响应创建一个空 select:

<%= 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 %>

然后当 selected 人口统计发生变化时,您可以更新 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>" );
      });

    });
  });

});

最后,您只需要在 ResponsesController 上执行索引操作即可为 select 框提供 json。您需要以下格式的 JSON。

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

这个动作应该会给你类似的东西:

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

现在,当第一个 select 中的人口统计数据发生变化时,您应该会在第二个 select 中获得过滤后的回复列表。如果这有效,您现在可以添加您选择的 JQuery 插件。就个人而言,我更喜欢 Chosen 而不是 Select2.

要在上述情况下选择工作,您只需稍微修改 Javascript:

$(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");
    });
  });

});