[英]How jQuery to change a second select list based on the Third select list option and second select based upon first
[英]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.