我有一个程序,其中 javascript 会更改几个复选框,根据其他复选框的选中情况来禁用、选中或取消选中它们。我注意到,如果您选中了一个复选框,然后将其禁用,则可以同时选中和禁用它。我不希望这成为可能。我希望任何被禁用的复选框也被取消选中。我一直在寻找一种简单的方法来做到这一点。我认为 queryselectorall 会起作用。这是一个简化的示例。在此示例中,我默认选中并禁用其中一个复选框。如果您单击另一个框,它应该取消禁用框中的选中状态。我以为这个简单的函数就可以做到这一点,但它不起作用。
function fixit() {
document.querySelectorAll('input[type="checkbox"]:checked:disabled').checked=0;
}
<form id='theform' name='mainform' method='post' action='#'>
box1<input onClick='fixit()' type='checkbox' disabled checked>
box2<input onClick='fixit()' type='checkbox'>
box3<input onClick='fixit()' type='checkbox'>
</form>
最佳答案
querySelectorAll
返回一个元素列表,该列表没有属性 checked
。您需要迭代元素列表并应用更改。
function fixit() {
var cbs = document.querySelectorAll('input[type="checkbox"]:checked:disabled');
for(var i = 0;i<cbs.length;i++){
cbs[i].checked = 0;
}
}
<form id='theform' name='mainform' method='post' action='#'>
box1<input onClick='fixit()' type='checkbox' disabled checked>
box2<input onClick='fixit()' type='checkbox'>
box3<input onClick='fixit()' type='checkbox'>
</form>
关于javascript - 防止复选框同时被选中和禁用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41516770/