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 關注
- 220 瀏覽
添加回答
舉報