gpt4 book ai didi

ruby-on-rails - Rails_Admin 相关的下拉菜单

转载 作者:行者123 更新时间:2023-12-04 03:15:23 24 4
gpt4 key购买 nike

有没有办法根据另一个下拉列表的值过滤下拉列表?
例如,如果我们有: ClassStudent 模型,其中 Studentclass_id;有没有办法根据所选的 Class 过滤下拉列表中显示的学生?

EDIT

显然,rails_admin gem 具有我正在寻找的 association 关系;但它并不完美。

最佳答案

给定两个 <select>元素 "Class""Student" , 与 Student列表包含 data-class_id属性引用来自 Class 的值列表(见下面的片段),你可以过滤 "Student"基于 "Class" 的下拉列表使用以下 vanilla-JavaScript 代码的下拉列表的值:

var firstSelectId = "Class";
var secondSelectId = "Student";
var data_attr = "class_id";
this.addEventListener("DOMContentLoaded", function(event) {
var firstSelect = document.getElementById(firstSelectId);
var secondSelect = document.getElementById(secondSelectId);
firstSelect.addEventListener("change", function(event) {
var value = event.target.value;
Array.prototype.forEach.call(secondSelect.options, function(item) {
item.style.display = (item.dataset[data_attr] === value) ? 'inline' : 'none';
});
var selected = secondSelect.selectedOptions[0];
if (selected && selected.dataset[data_attr] !== event.target.value) {
secondSelect.selectedIndex = -1;
}
});
firstSelect.dispatchEvent(new Event('change'));
});
<form id="myform">
Select a class and student:
<select id="Class">
<option value="1">Class1</option>
<option value="2">Class2</option>
<option value="3">Class3</option>
</select>
<select id="Student">
<option value="StudentA" data-class_id="1">A</option>
<option value="StudentB" data-class_id="2">B</option>
<option value="StudentC" data-class_id="3">C</option>
<option value="StudentD" data-class_id="2">D</option>
<option value="StudentE" data-class_id="1">E</option>
<option value="StudentF" data-class_id="1">F</option>
</select>
</form>

关于ruby-on-rails - Rails_Admin 相关的下拉菜单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41504138/

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