加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – Ruby on Rails – 更改事件的下拉框

发布时间:2020-12-16 19:57:16 所属栏目:百科 来源:网络整理
导读:我的应用程序中有两个下拉框. 根据第一个组合框中选择的值,第二个下拉框中的值应该被填充.这些值应来自数据库. 请帮帮我. 解决方法 这是一个使用 jquery-ujs(https://github.com/rails/jquery-ujs)的干净方法 在你看来: %= select_tag :first_select,# name
我的应用程序中有两个下拉框.
根据第一个组合框中选择的值,第二个下拉框中的值应该被填充.这些值应来自数据库.

请帮帮我.

解决方法

这是一个使用 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);
    });
  });

});

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读