javascript - 根据 Rails 中的第一个选择列表值更改第二个选择列表

标签 javascript jquery ruby-on-rails ruby

更新了底部的答案代码

对于第二个选择框,仅显示与所选团队相关联的那些员工的选择选项。

表格:

enter image description here


示例:用户选择另一个团队。工作人员选择选项更新以仅显示与所选团队关联的那些工作人员。

enter image description here

我知道解决方案是使用 javascript,但我在 Rails 环境中应用它时遇到了问题。我知道 this question但我仍然无法将其应用于我的 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

有了这个,在你的 ajax 调用的 success 回调中,你会得到一个包含列表的 JSON 对象。因此,您需要清除 staff 选择并创建选项并附加到它。

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

如您所见,我没有将创建选项的代码放入列表中,但简单的搜索将有大量关于此的结果。这个想法很简单。

关于javascript - 根据 Rails 中的第一个选择列表值更改第二个选择列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31612461/

相关文章:

ruby-on-rails - has_many 通过复选框

ruby-on-rails - 如何在 Cucumber/Capybara 中设置浏览器语言?

javascript - 使用 Django 和 Angular 的 CORS 预检请求

javascript - 带有 InfoBubbles 的 Google map

javascript - 将原型(prototype)继承给 JavaScript 中的所有子元素

jquery - 点击div外部如何向上滑动?

ruby-on-rails - rails : How Does csrf_meta_tag Work?

javascript - 在固定表头中遇到 overflow-x 问题

javascript - 如何检查 jquery 中的 .blur() 是否单击了特定项目

javascript - CSS 的数据属性不是很有用吗?