gpt4 book ai didi

javascript - 选择主下拉菜单并强制其他下拉菜单选择具有相同值的选项

转载 作者:行者123 更新时间:2023-12-01 05:20:02 25 4
gpt4 key购买 nike

主下拉列表发生变化时,我希望其他下拉列表也相应发生变化。

但我不知道为什么只有第一个其他下拉菜单起作用,而第二个下拉菜单却无法相应地更改其值。我我知道如果我将第二个下拉列表的名称更改为与第一个下拉列表相同的名称,它将起作用。

但是由于它们是要保存在数据库中的不同字段,因此名称必须不同。

任何解决方案将不胜感激。非常感谢。

function setDropDown() {
var index_name =
document.getElementsByName('ForceSelection')[0].selectedIndex;
var others = document.getElementsByName('Qualifications');
for (i = 0; i < others.length; i++)
others[i].selectedIndex = index_name;

var others2 = document.getElementsByName('Qualifications2');
for (i = 0; i < others2.length; i++)
others2[i].selectedIndex = index_name2;
}
Primary dropdown<select name="ForceSelection" id="ForceSelection" onChange="javascript:return setDropDown();">
<option value="" selected>Select</option>
<option value="treatmentid1">treatmentname1</option>
<option value="treatmentid2">treatmentname2</option>
</select> other dropdown
<select id="Qualifications" name="Qualifications">
<option value="select">select</option>
<option value="treatmentid1">treatmentname1</option>
<option value="treatmentid2">treatmentname2</option>
</select> other dropdown2
<select id="Qualifications2" name="Qualifications2">
<option value="select">select</option>
<option value="treatmentid1">treatmentname1</option>
<option value="treatmentid2">treatmentname2</option>
</select>

最佳答案

将 css 类添加到辅助下拉列表中,并使用 document.querySelectorAll 一次获取所有内容。

然后您可以使用单个循环来更新其selectedIndex

function setDropDown() {
var index_name =
document.getElementsByName('ForceSelection')[0].selectedIndex;
var others = document.querySelectorAll('.secondary');
for (var i = 0; i < others.length; i++) {
others[i].selectedIndex = index_name;
}

}
div {
padding: 15px;
}
<div><b>Primary dropdown:</b>
<select name="ForceSelection" id="ForceSelection" onChange="javascript:return setDropDown();">
<option value="" selected>Select</option>
<option value="treatmentid1">treatmentname1</option>
<option value="treatmentid2">treatmentname2</option>
</select>
</div>
<div>
<b>Other dropdown 1</b>:
<select class='secondary' id="Qualifications" name="Qualifications">
<option value="select">select</option>
<option value="treatmentid1">treatmentname1</option>
<option value="treatmentid2">treatmentname2</option>
</select></div>
<div> <b>Other dropdown 1</b>:
<select class='secondary' id="Qualifications2" name="Qualifications2">
<option value="select">select</option>
<option value="treatmentid1">treatmentname1</option>
<option value="treatmentid2">treatmentname2</option>
</select>
</div>

关于javascript - 选择主下拉菜单并强制其他下拉菜单选择具有相同值的选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45228135/

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