与jquery-select2相关的下拉内容

时间:2022-11-27 18:41:14

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.

我有一个Rails 4应用程序,我在其中使用Jquery-select2作为下拉列表。我有两个下拉菜单,我想让用户在第一个下拉菜单中选择什么,用户可以在第二个下拉菜单中选择什么。有点像选择一个国家,并被给予一个国家的名单。

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.

在开始使用Select2之前,我已经让它正常工作了。但是,我忽略了如何让它与Select2一起工作的一些细微差别。我非常喜欢Rails,但Javascript和Jquery是我的弱点。

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:

以下是我在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:

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

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

但是,我尝试过的一切都失败了。我看过这个,这个和这个,但是没有一个是Rails相关的,所以我被卡住了。

Any ideas?

什么好主意吗?

All help is greatly appreciated.

非常感谢大家的帮助。

2 个解决方案

#1


2  

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.

从最简单的情况开始:首先,让表单在没有Select2或Chosen等条件下运行。只需使用基本的选择下拉菜单,就可以看到发生了什么。

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

在您的情况下,您可以加载所有的人口统计数据,并为响应创建一个空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 %>

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

然后,当选定的人口结构发生变化时,您可以通过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.

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

[{"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.

现在,当你的人口结构在第一个选择中发生变化时,你应该在第二个选择中得到一个经过过滤的响应列表。如果这是可行的,您现在可以添加您选择的JQuery插件。就我个人而言,我更喜欢选择2。

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

要在上述情况下选择工作,只需稍微修改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");
    });
  });

});

#2


1  

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

我不知道rails,但是我用了Javasctipt/Jquery引导。

Is this solve your problem.

这能解决你的问题吗?

I binding country and state values from Javascript Array.

从Javascript数组绑定国家和状态值。

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

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

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

#1


2  

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.

从最简单的情况开始:首先,让表单在没有Select2或Chosen等条件下运行。只需使用基本的选择下拉菜单,就可以看到发生了什么。

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

在您的情况下,您可以加载所有的人口统计数据,并为响应创建一个空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 %>

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

然后,当选定的人口结构发生变化时,您可以通过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.

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

[{"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.

现在,当你的人口结构在第一个选择中发生变化时,你应该在第二个选择中得到一个经过过滤的响应列表。如果这是可行的,您现在可以添加您选择的JQuery插件。就我个人而言,我更喜欢选择2。

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

要在上述情况下选择工作,只需稍微修改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");
    });
  });

});

#2


1  

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

我不知道rails,但是我用了Javasctipt/Jquery引导。

Is this solve your problem.

这能解决你的问题吗?

I binding country and state values from Javascript Array.

从Javascript数组绑定国家和状态值。

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

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

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