【问题标题】:Ruby on Rails - drop down box on change eventRuby on Rails - 更改事件的下拉框
【发布时间】:2012-11-29 01:33:09
【问题描述】:

我的应用程序中有两个下拉框。 根据在第一个组合框中选择的值,应填充第二个下拉框中的值。这些值应来自数据库。

请帮帮我。

【问题讨论】:

    标签: ruby-on-rails ruby


    【解决方案1】:

    这是一个使用 jquery-ujs (https://github.com/rails/jquery-ujs) 的干净方法

    在你看来:

    <%= 
      select_tag  
          :first_select, # name of selectbox
          options_from_collection_for_select(@myrecords, "id", "name"), # your options for this select box
          :'data-remote' => 'true', # important for UJS
          :'data-url' => url_for(:controller => 'MyController', :action => 'getdata'), # we get the data from here!
          :'data-type' => 'json' # tell jQuery to parse the response as JSON!
    %>
    
    
    <%= 
       select_tag  
           :second_select, # name of selectbox
           "<option>Please select something from first select!</option>"
    %> 
    

    你的控制器:

    class MyController < ApplicationController
    
    
      def getdata
        # this contains what has been selected in the first select box
        @data_from_select1 = params[:first_select]
    
        # we get the data for selectbox 2
        @data_for_select2 = MyModel.where(:some_id => @data_from_select1).all
    
        # render an array in JSON containing arrays like:
        # [[:id1, :name1], [:id2, :name2]]
        render :json => @data_for_select2.map{|c| [c.id, c.name]}
      end
    end
    

    在您的 application.js 中:

    $(document).ready(function() {
    
      // #first_select is the id of our first select box, if the ajax request has been successful,
      // an ajax:success event is triggered.
    
      $('#first_select').live('ajax:success', function(evt, data, status, xhr) {
        // get second selectbox by its id
        var selectbox2 = $('#second_select');
    
        // empty it
        selectbox2.empty();
    
        // we got a JSON array in data, iterate through it
    
        $.each(data, function(index, value) {
          // append an option
          var opt = $('<option/>');
    
          // value is an array: [:id, :name]
          opt.attr('value', value[0]);
          // set text
          opt.text(value[1]);
          // append to select
          opt.appendTo(selectbox2);
        });
      });
    
    });
    

    【讨论】:

    • getdata 的路由是什么样的?
    • 我希望这可能对某人有所帮助,getdata 路由看起来像“get 'getdata' => 'controller#getdata”
    【解决方案2】:

    您可以从我的项目中获得灵感。它会根据所选国家/地区更新状态。 它利用Carmen 一个伟大的宝石列表国家,州等......

    查看:

    <p>
      <label>Country <span>*</span></label>
      <%= profile_form.select(:country,Carmen.countries, {:include_blank => 'Select a Country'}, :id => "profile_country") %>
    </p>
    <p>
      <label>State <span>*</span></label>
      <%= profile_form.select(:state,  "" , {:include_blank => 'Select a Country first'}, :id => "profile_state") %>
    </p>
    

    jQuery 代码:

    $('#profile_country').change(function() {
      if ($(this).val() == '')
        {
        $('#profile_state').html( $('<option>No state provided for your country</option>'));
        }
      else {
       $.ajax({
        type: "GET",
        url: "/remote/get_states/" + encodeURIComponent($(this).attr('value')),
        success: function(data){
           if (data.content == 'None')  //handle the case where no state related to country selected
             {
             $('#profile_state').empty();
             $('#profile_state').append( $('<option>No state provided for your country</option>'));
             }
            else
             {
             $('#profile_state').empty();
             $('#profile_state').append( $('<option>Select your State</option>'));
             jQuery.each(data,function(i, v) {
               $('#profile_state').append( $('<option value="'+ data[i][1] +'">'+data[i][0] +'</option>'));
             });
           }
         }
       });
     }
    });
    

    控制器:

    def states
      begin
        render :json => Carmen::states(CGI::unescape(params[:country]))
      rescue 
        render :json => {"content" => "None"}.to_json
      end
    end   
    

    【讨论】:

      【解决方案3】:

      我就是这样做的。在 Rails 3.2 中工作

      查看:

      <%= select_tag :major_category_select_id, options_from_collection_for_select(@majorcategories, 'id', 'name'), :'data-remote' => 'true', :'data-url' => url_for(:controller => 'listings', :action => 'submit_major_category', format: 'js') %>
      

      控制器方法:

      def submit_major_category
          @major_category = MajorCategory.find(params[:major_category_select_id])
          @minor_categories = @major_category.minor_categories
      
          respond_to do |format|
            # format.html { render partial: 'minor_categories_select' }
            format.js
          end
        end
      

      路线:

      get "listings/submit_major_category"
      

      然后创建一个得到响应的submit_major_category.js.erb 文件。

      【讨论】:

      • Excelent 是最好的方法,就像使用原型一样。 +1
      • 是否可以在rails 5中使用
      猜你喜欢
      • 1970-01-01
      • 2013-06-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-16
      • 1970-01-01
      • 2017-09-08
      • 2014-08-04
      相关资源
      最近更新 更多