gpt4 book ai didi

javascript - 嵌套表单 rails 中的动态选择

转载 作者:行者123 更新时间:2023-12-03 02:00:40 25 4
gpt4 key购买 nike

js 如何获取下拉列表中选定的值并将其传递给 Controller ​​,以便它返回另一个下拉列表的名称列表?

到目前为止我已经做了什么:沙门氏菌.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>

沙门氏菌_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>

沙门氏菌.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

沙门氏菌.js

 $(function () {
$(document).on('change', "#mode_change", function () {
var selectedText = $(this).find("option:selected").text();
var selectedValue = $(this).val();
alert("Selected Text: " + selectedText);
});
});

最佳答案

ID 在您的 DOM 上必须是唯一的。您正在为 divselect 标记复制它们。首先更改它们并使用它来获取所选选项的值

$(document).on('change', ".mode_change", function () {
var selectedText = $(this).find("option:selected").text();
var selectedValue = $(this).val();
...

关于javascript - 嵌套表单 rails 中的动态选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50051140/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com