首页 > 解决方案 > Groovy 循环遍历 SELECT 并修改复选框

问题描述

我有一个包含三个选项和多个复选框的选择。

<select id="mySelect">
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
<option value="option3">Option 3</option>
</select>

<div>
<input id="checkbox1" type="checkbox" value="checkbox1">Checkbox 1
<input id="checkbox2" type="checkbox" value="checkbox2">Checkbox 2
<input id="checkbox3" type="checkbox" value="checkbox3">Checkbox 3
</div>

我想使用 Groovy 根据在选择中选择的选项更改哪些复选框是可见的。

例如,如果选择了 option1,则仅应显示 checkbox1。如果选择了 option1 和 option3,则应该显示 checkbox1 和 checkbox3。ID 并不总是匹配的(例如,如果我愿意,option1 可能会显示 checkbox3 而不是 checkbox1)。

我想我需要某种针对复选框的选项映射表,然后遍历选项并显示正确的复选框。

我可以使用多个 if 语句(如果 mySelect 等于 option1 然后显示 X 等),但多个 if 语句会非常难看。如果有更好的方法来循环执行此操作,我将不胜感激。

谢谢

标签: javascriptloopsselect

解决方案


你可以这样做: -

HTML - 向复选框包装器添加一个类

<div class="checkbox-container">
    <input id="checkbox1" type="checkbox" value="checkbox1">Checkbox 1
    <input id="checkbox2" type="checkbox" value="checkbox2">Checkbox 2
    <input id="checkbox3" type="checkbox" value="checkbox3">Checkbox 3
</div>

JS

const selectEelement = document.getElementById("mySelect");

selectEelement.addEventListener('change', function() {
    var selectedValue = selectEelement.options[e.selectedIndex].value;
    var checkboxId = `checkbox${selectedValue.substr(selectedValue.length-1)}`;

    // First hide all the checkboxes
    document.querySelector('.checkbox-container').style.visibility = "hidden";

    // then show a particular checkbox
    document.getElementById(checkboxId).style.visibility = "visible";
});

推荐阅读