我有一个包含5个select元素的表单,每个元素具有与其他选择元素相同的选项,现在我希望每个选项仅被选择一次,因此我需要代码来实现以下目的:
我都实现了这两项,但是我的代码仅适用于2个选择,但是如果我在用户将选择号更改为3或更高时添加了更多选择,则将在较低选择中启用旧选项
我的代码:
{
"cat": "error",
"topic": "glp/0/17q2d9v/rq/dev/iox/dio/do",
"message": "ERROR in iox_test handle",
"utc": "2018-07-12 12:39:43.20 UTC"
}
答案 0 :(得分:1)
首先添加阵列中所有复选框中的所有选定选项。
然后遍历其他选择框中的每个选项,并查看值是否存在。 这是更新的js函数。
function updateDepartments2(event) {
var selectNodes = document.getElementsByClassName("choice");
var x = [];
for (node of selectNodes) {
var opt = node.options[node.selectedIndex].value;
x.push(opt);
}
for (node of selectNodes) {
if (node !== event.target) {
for (child of node) {
if (x.includes(String(child.index))) {
var disabledState = "disabled"
} else {
var disabledState = ""
}
node[child.index].disabled = disabledState
}
if (node.selectedIndex == event.target.selectedIndex) {
node.selectedIndex = 0
}
}
}
}
更新的小提琴 https://jsfiddle.net/se1dofzb/1/
更新2: 我已经从头开始重新设计了您的功能,请检查是否有任何错误或澄清。
function updateDepartments2(event) {
var selectNodes = document.getElementsByClassName("choice");
var x = [];
for (var node of selectNodes) {
if (node.selectedIndex != 0)
x.push(node.selectedIndex);// Add index of all selected elements
}
for (var node of selectNodes) {
for (var child of node) {
//Traverse all option in every select box
var disabledState;
if (x.includes(child.index)) {
//If it is selected, disable it
disabledState = "disabled"
} else {
disabledState = ""
}
node[child.index].disabled = disabledState
}
}
}
答案 1 :(得分:0)
在选择更改时调用该函数并获取选项索引。获取所有选择元素并禁用选择元素中的选定选项
function a(e)
{
console.log(e.selectedIndex)
var k=document.querySelectorAll('select')
for(let i=0;i<k.length;i++)
{
if(k[i]!=e)
k[i].options[e.selectedIndex].setAttribute("disabled","disabled")
}
}
function d()
{
var k=document.querySelectorAll('select')
for(let i=0;i<k.length;i++)
{
var c=k[i].querySelectorAll('option');
for(let i=0;i<c.length;i++)
c[i].removeAttribute("disabled")
}
}
<!DOCTYPE html>
<html>
<body>
Person Number 1
<select id="choice1" name="choice1" class="choice" onchange="a(this)">
<option value="null">Please Select an option</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<br/>
Person Number 2
<select id="choice2" name="choice2" class="choice" onchange="a(this)">
<option value="null">Please Select an option</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<br/>
Person Number 3
<select id="choice3" name="choice3" class="choice" onchange="a(this)">
<option value="null">Please Select an option</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<br>
<input type="button" onclick="d()" value="Reset">
</body>
</html>