根据Rails中的第一个选择列表值更改第二个选择列表 [英] Change second select list based on first select list value in rails
问题描述
已在底部添加了答案代码
对于第二个选择框,仅显示与所选team
关联的那些staff members
的选择选项.
For second select box, show select options for only those staff members
associated to the selected team
.
表格:
示例案例:用户选择另一个团队.职员选择选项将更新,以仅显示与所选团队相关联的那些职员.
Example case: A user selects another team. The staff member select options updates to display only those staff members associated with that selected team.
我知道解决方案是使用javascript的,但是在Rails环境中应用它时遇到了麻烦.我知道
I know the solution is with javascript, but I'm having trouble applying it within a rails environment. I am aware of this question but am still having trouble applying it to my rails app.
代码
#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
必须在您的路由中存在).
First you fire an ajax
call to your controller
. (Keep in mind that this url
from the ajax
call must exist in your routes).
$(document).ready(function() {
$("#team").on('change', function(){
$ajax({
url: "populate_other_list",
type: "GET",
data: {team_id: $(this).val()},
// Callbacks that will be explained
})
});
接下来,将action
放入controller
中.
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
这样,在ajax
调用的success
回调中,您将获得一个带有列表的JSON
对象.因此,您需要清除staff
选择并创建选项并将其追加.
With this, on your success
callback of your ajax
call, you get a JSON
object with your list. So you need to clear the staff
select and create the options and append to it.
// Ajax call
success: function(data) {
$("#staff_member_id").children().remove();
// Create options and append to the list
}
// Rest of Ajax call
如您所见,我没有将创建选项的代码放入列表中,但是简单的搜索将获得大量结果.这个想法很简单.
As you can see, i didn't put the code that create the options and put them inside the list, but a simple search will have plenty of results about this. The idea is simple though.
这篇关于根据Rails中的第一个选择列表值更改第二个选择列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!