javascript - 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 语句会非常难看。如果有更好的方法来循环执行此操作,我将不胜感激。
谢谢
解决方案
你可以这样做: -
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";
});
推荐阅读
- c# - 如何在 C# 中加载 COM 实例
- javascript - 如何使用联邦快递追踪号码下载联邦快递货件标签?
- java - 替换匹配 XML 标记的内容
- c# - 如何使用单选按钮进行测验?
- javascript - 创建一个打印 # 符号而不是数字值的 for 循环
- python - 在 Opencv Python 中的 BitWise 掩码中查找最高点
- r - 轴标签在ggplot2中消失了
- javascript - 在反应 js 中切换 div 可见性
- arrays - Xml 到具有多个 LineItems 的 Json
- postgresql - 在 PostgreSQL 中查找差异 DISTINCT 列的值