jquery - jquery-select2 的依赖下拉内容

标签 jquery ruby-on-rails coffeescript jquery-select2

我有一个 Rails 4 应用程序,我在其中使用 Jquery-select2 作为下拉列表。我有两个下拉菜单,我希望第一个下拉菜单中的选择确实决定了用户可以在第二个下拉菜单中选择的内容。有点像选择一个国家/地区并获得该国家/地区的州列表。

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

在开始使用 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>

这是我发现并修改的一些 CoffeeScript,并且在 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 之前使用的响应模型下拉列表的代码行是:

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

但是,我所尝试的一切都失败了。我看过thisthisthis ,但它们都与 Rails 无关,所以我陷入困境。

有什么想法吗?

非常感谢所有帮助。

最佳答案

从最简单的情况开始:首先,让表单在没有 Select2 或 Chosen 等的情况下工作。只需使用基本的选择下拉菜单,即可查看正在发生的情况。

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

<%= 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 更新响应选项:

$(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。

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

现在,当您的人口统计在第一个选择中发生变化时,您应该在第二个选择中获得过滤后的响应列表。如果这有效,您现在可以添加您选择的 JQuery 插件。我个人更喜欢Chosen选择2。

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

});

关于jquery - jquery-select2 的依赖下拉内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33617331/

相关文章:

javascript - 动态 FLOT 图例表

ruby-on-rails - rails4 中的未定义方法 `user?'

ruby-on-rails - rails + 新遗物 : What does RPM mean?

ruby-on-rails - 将 rails 2 生成器转换为 rails 3?

node.js - Swagger UI 不发送 url 参数

javascript - FramerJS:重新排序数组

node.js - 使用coffeescript的 Node 中的全局变量

javascript - 追加时,对新创建的 div 进行计数,并在追加新 div 时销毁该 div

javascript - 单击另一个按钮时是否可以隐藏 div?

javascript - jquery.mobile 滑动页面导航限制为 div 元素