簡體   English   中英

根據rails中的第一個選擇列表值更改第二個選擇列表

[英]Change second select list based on first select list value in rails

更新了底部的答案代碼

對於第二個選擇框,僅顯示與所選team關聯的staff members選擇選項。

形成:

在此輸入圖像描述


示例案例 :用戶選擇另一個團隊。 工作人員選擇選項更新以僅顯示與所選團隊相關聯的工作人員。

在此輸入圖像描述

我知道解決方案是使用javascript,但我在rails環境中應用它時遇到了麻煩。 我知道這個問題,但仍然無法將其應用到我的rails應用程序。


#app/controllers/task_notes_controller.rb
...
def new
  @task_note = TaskNote.new
  @teams = Team.all.includes(:staff_members)
end
...


#app/views/task_notes/_form.html.erb
...
<%= select_tag('team', options_from_collection_for_select(@teams, :id, :name ) ) %>

<div class="field">
  <%= f.label :staff_member_id %><br>
  # Currently displays all staff members on every team, no matter what team is selected.
  <%= f.collection_select :staff_member_id, StaffMember.all, :id, :first_name %>
</div>
...


#app/assets/javascripts/task_notes.js
$(document).ready(function(){

  $("#team").on('change', function(){
      alert("The new team id is: " + $(this).val() ); 
      # The value (the id of the team) does update on selection option change.  
      # Now I need to specify that I want the select options for the staff members
      # select box to update and show only staff members with this team_id 
  });

});

首先,您向controller發出ajax調用。 (請記住,來自ajax調用的url必須存在於您的路由中)。

$(document).ready(function() {
  $("#team").on('change', function(){
    $ajax({
      url: "populate_other_list",
      type: "GET",
      data: {team_id: $(this).val()},
      // Callbacks that will be explained
    })
  });

接下來,您將在controller內部進行action

def populate_other_list
  team_id = params[:team_id]
  @staff = Staff.find_by team_id: team_id
  respond_to do |format|
    format.json { render json: @staff }
  end
end

有了這個,在你success回調你的ajax調用時,你會得到一個包含你的列表的JSON對象。 因此,您需要清除staff選擇並創建選項並附加到其中。

// Ajax call
success: function(data) {
  $("#staff_member_id").children().remove();
  // Create options and append to the list
}
// Rest of Ajax call

正如您所看到的,我沒有放置創建選項的代碼並將它們放在列表中,但是簡單的搜索將會有很多結果。 這個想法很簡單。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM