3 回答
TA贡献1801条经验 获得超8个赞
您可以使用querySelectorAll查找不是关键复选框 ( none) 的复选框集合,并根据关键复选框的状态对每个复选框禁用/启用它,如下所示:
document.addEventListener('DOMContentLoaded',e=>{
document.querySelector('input[type="checkbox"][name="none"]').addEventListener('click',function(e){//find all checkboxes that are NOT the key checkbox
let col=document.querySelectorAll('input[ type="checkbox" ]:not( [ name="none" ] )');
col.forEach(chk=>{//iterate through collection
chk.disabled=this.checked;//disable current checkbox if key is checked and enable if not checked
if( this.checked )chk.checked=false;//if key checkbox is checked, all others cannot be checked
});
});
});
<table>
<tr>
<td width="100px">1. Cough</td>
<td width="80px"><input type="hidden" name="cough" value="no"><input type="checkbox" class="form-control" name="cough" value="yes"></td>
</tr>
<tr>
<td width="100px">2. Sore Throat</td>
<td width="80px"><input type="hidden" name="sore_throat" value="no"><input type="checkbox" class="form-control" name="sore_throat" value="yes"></td>
</tr>
<tr>
<td width="100px">3. Fever</td>
<td width="80px"><input type="hidden" name="fever" value="no"><input type="checkbox" class="form-control" name="fever" value="yes"></td>
</tr>
<tr>
<td width="100px">4. Flu</td>
<td width="80px"><input type="hidden" name="flu" value="no"><input type="checkbox" class="form-control" name="flu" value="yes"></td>
<tr>
<td width="230px">5. None of above</td>
<td width="80px"><input type="hidden" name="none" value="no"><input type="checkbox" class="form-control" name="none" value="yes"></td>
</tr>
</table>
TA贡献1895条经验 获得超7个赞
超文本标记语言
<table id="sickness">
JS
var checkboxes = document.getElementById("sickness").getElementsByTagName("input");
var names = ["cough", "sore_throat", "fever","flu"];
checkboxes.namedItem("none").addEventListener("change", function(e){
if(this.checked == true){
for(var i=0;i<names.length;i++){
checkboxes.namedItem(names[i]).disabled = true;
}
}else{
for(var i=0;i<names.length;i++){
checkboxes.namedItem(names[i]).disabled = false;
}
}
});
TA贡献1884条经验 获得超4个赞
纯CSS解决方案:
将 id= 添加到控制复选框
将 class=dohidepottially 添加到受控表行
添加CSS样式:
#none:checked + table .dohidepotentially {display: none}
唯一的缺点是控制复选框必须放在表格之前(对于 css 相邻选择器)。但它可以被隐藏。
缩短的示例:
<form>
<input type="checkbox" class="form-control" name="none" value="yes" id="none">
<table>
<tr class="dohidepotentially">
<td width="100px">2. Sore Throat</td><td width="80px"><input type="hidden" name="sakit_tekak" value="no"><input type="checkbox" class="form-control" name="sore_throat" value="yes"></td>
</tr>
<tr>
<td width="100px">3. Fever</td><td width="80px"><input type="hidden" name="fever" value="no"><input type="checkbox" class="form-control" name="fever" value="yes"></td>
</tr>
<tr>
<td width="230px">5. None of above</td><td width="80px"><input type="hidden" name="none" value="tiada"><label for="none">[click here]</label></td>
</tr>
</table>
</form>
- 3 回答
- 0 关注
- 150 浏览
添加回答
举报