使用jquery-select2的相关下拉内容

时间:2015-11-09 20:06:49

标签: 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" %>

但是,我尝试过的一切都失败了。我查看了thisthis以及this,但没有一个与Rails相关,所以我被卡住了。

有什么想法吗?

非常感谢所有帮助。

2 个答案:

答案 0 :(得分:3)

从最简单的情况开始:首先,只需让表单在没有Select2或Chosen的情况下工作,或者其他什么。只需使用基本的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 %>

然后,当选定的受众特征更改时,您可以更新针对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来选择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");
    });
  });

});

答案 1 :(得分:1)

我不知道铁轨, 但我使用了Javasctipt / Jquery,Bootstrap。

这是否解决了你的问题。

我从Javascript Array绑定国家/地区和州的值。

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

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