Ruby on Rails - drop down box on change event

后端 未结 3 1552
眼角桃花
眼角桃花 2020-12-05 01:05

I have two drop down boxes in my application. Based on the value selected in 1st combobox, the values in 2nd drop down box should be populated.And these values should come f

3条回答
  •  無奈伤痛
    2020-12-05 01:31

    here's a clean approach using jquery-ujs (https://github.com/rails/jquery-ujs)

    In your view:

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

    Your Controller:

    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
    

    In your 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 = $('

提交回复
热议问题