带有jquery-select2的从属下拉列表内容 [英] Dependent Dropdown Contents with jquery-select2

查看:80
本文介绍了带有jquery-select2的从属下拉列表内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Rails 4应用,我在其中使用Jquery-select2作为下拉列表.我有两个下拉菜单,我希望第一个下拉菜单中的内容决定用户在第二个下拉菜单中可以选择的内容.就像选择一个国家并获得该国家的州列表一样.

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.

在开始使用Select2之前,我已经完成了这项工作.但是,我缺少如何使其与Select2配合使用的某些细微差别.我对Rails是如此,但是Javascript和Jquery是我的弱点.

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.

这是我的表格:

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

这是我发现和修改的某些CoffeeScript,并且在Select2之前可以使用:

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

在Select2之前用于响应模型下拉菜单的代码行是:

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

当我看到它时,似乎需要以某种方式将:responses, :demographic_name,移至该行:

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

但是,我尝试过的所有方法都失败了.我看过 this ,但是它们都不与Rails相关,所以我被卡住了.

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.

有什么想法吗?

非常感谢所有帮助.

推荐答案

从最简单的情况开始:首先,只需在不使用Select2或Chosen或其他任何东西的情况下使表格起作用.只需使用基本的选择"下拉列表,您就可以看到正在发生的事情.

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

然后,当所选择的人口变化,可以更新用于响应超过AJAX的选项:

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

    });
  });

});

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

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

现在,当您的受众特征"在第一个选择中发生更改时,您应该在第二个选择中获得响应"的过滤列表.如果此方法有效,则现在可以添加您选择的JQuery插件.就个人而言,我更喜欢选择而不是Select2.

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.

要选择在上述情况下可以正常工作,您只需对Javascript进行一些修改:

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

});

这篇关于带有jquery-select2的从属下拉列表内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆