js如何在下拉列表中获取所选值并将其传递给控制器,以便它返回另一个下拉列表的名称列表?
到目前为止我做了什么: salmonellas.js
$(function () {
$('body').on('change', "#mode_change", function () {
var selectedText = $(this).find("option:selected").text();
var selectedValue = $(this).val();
if (selectedText) {
$.get('/salmonellas/find_stages?mode_title='+ selectedText, function(selectedText) {
return $(selectedText).html();
});
}
});
});
沙门氏菌/ form.html.erb
<div class="process_salmonellas">
<% f.simple_fields_for :process_salmonellas do |process_salmonella| %>
<%= render 'process_salmonella_fields', :f => process_salmonella %>
<% end %>
</div>
沙门氏菌/ _process_salmonella_fields.html.erb
<div class="mode_change" id="mode_change">
<%= f.collection_select :title, Mode.order(:name), :id, :name, class: 'mode_change', id:'mode_change', include_blank: true, "data-content": :mode_id%>
</div>
<h4>Stage</h4>
<div class="stage">
<% f.simple_fields_for :stages do |stage| %>
<%= render 'stage_fields', :f => stage %>
<% end %>
</div>
沙门氏菌/ _stage_fields.html.erb
<div class="form-inputs">
<%= f.grouped_collection_select :title, Mode.order(:name), :steps, :name, :id, :name, class: "step_selection" %>
</div>
salmonellas_controller.rb
def find_stages
@mode = Mode.where("name = ?", params[:mode_title])
@steps = @mode.steps
end
正在寻找另一种模式,为什么必须预先注册这些字段。我正在使用茧让它嵌套。
更新
沙门氏菌/ _process_salmonella_fields.html.erb
<div class="form-inputs">
<%= f.collection_select :title, Mode.order(:name), :id, :name, class: 'mode_change', id:'mode_change', include_blank: true, "data-content": :mode_id%>
</div>
<h4>Stage</h4>
<div class="stage">
<% f.simple_fields_for :stages do |stage| %>
<%= render 'stage_fields', :f => stage %>
<% end %>
</div>
更新2
沙门氏菌/ _process_salmonella_fields.html.erb
<div class="form-inputs">
<%= f.collection_select :title, Mode.order(:name), :id, :name, id:'mode_change', include_blank: true %>
</div>
salmonellas.js
$(function () {
$('body').on('change', ".mode_change", function () {
var selectedText = $(this).find("option:selected").text();
var selectedValue = $(this).val();
if (selectedText) {
$.get('/salmonellas/find_stages?mode_title='+ selectedText, function(selectedText) {
return $(selectedText).html();
});
}
});
});
更新3
salmonellas.js
$(function () {
$(document).on('change', "#mode_change", function () {
var selectedText = $(this).find("option:selected").text();
var selectedValue = $(this).val();
alert("Selected Text: " + selectedText);
});
});
答案 0 :(得分:1)
您的DOM上的ID必须是唯一的。您正在复制div
和select
代码。首先更改它们并使用它来获取所选选项的值
$(document).on('change', ".mode_change", function () {
var selectedText = $(this).find("option:selected").text();
var selectedValue = $(this).val();
...