gpt4 book ai didi

javascript - html select 元素,其选项取决于另一个 select

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

我有两个选择元素,我想根据用户在第一次选择时选择的内容在第二次选择中显示一些选项。考虑首先选择有两个选项:a,b ...如果用户从第一个选择中选择“a”:第二个选择选项应该是 -> c , d ...如果用户从第一个选择中选择“b”:第二个选择选项应该是: e , f ...我已经完成了一些编码,但问题出在开始时,当用户没有从第一个选择中选择任何选项时,第二个选择始终为空(它应该显示 c , d)

<!DOCTYPE html>
<html>
<body>
<select id="s1" required>
<option value="a">a</option>
<option value="b">b</option>
</select>
<select id="s2" required > </select>
<script>
document.getElementById("s1").onchange = function() {
document.getElementById('s2').disabled = false; //enabling s2 select
document.getElementById('s2').innerHTML = ""; //clear s2 to avoid conflicts between options values
var opt0 = document.createElement('option');
var opt1 = document.createElement('option');
if (this.value == 'a') {
opt0.textContent = "c";
opt1.textContent = "d";
document.getElementById('s2').appendChild(opt0);
document.getElementById('s2').appendChild(opt1);
} else if (this.value == 'b') {
opt0.textContent = "e";
opt1.textContent = "f";
document.getElementById('s2').appendChild(opt0);
document.getElementById('s2').appendChild(opt1);
}
};
</script>
</body>
</html>

最佳答案

如果您可以将选项值保存在查找对象(或 JSON)中:

function setOptions(select, values) {
for (var i = select.length = values.length; i--; )
select[i].innerText = values[i]
}
function value(select) { return select.value || select[0].value } // 1st item by default

var data = { 1: { 1.1: [1.11, 1.12], 1.2: [1.21, 1.22] },
2: { 2.1: [2.11, 2.12], 2.2: [2.21, 2.22], 2.3: [2.31, 2.32, 2.33] } }

s2.onchange = function() { setOptions(s3, data[value(s1)][value(s2)]) }
s1.onchange = function() { setOptions(s2, Object.keys(data[value(s1)])); s2.onchange() }

setOptions(s1, Object.keys(data)); s1.onchange(); // fill the options
<select id=s1 required size=3></select>
<select id=s2 required size=3></select>
<select id=s3 required size=3></select>

关于javascript - html select 元素,其选项取决于另一个 select,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47502370/

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