我试图在单击其他复选框时启用和禁用多个复选框。
如果 Cash
或 Square 中的任何一个,我想禁用
或 box1
、box2
、box3
Paypal
已选中。否则,我想启用 box1
、box2
、box3
。
我目前有这段代码:
var check = $("#checkit1");
$("#checkit1").on('click',checkStatus);
function checkStatus(){
if(check.is(':checked'))
{
$("#click1").prop('disabled', true);
$("#click2").prop('disabled', true);
$("#click3").prop('disabled', true);
}
else{
$("#click1").prop('disabled', false);
$("#click2").prop('disabled', false);
$("#click3").prop('disabled', false);
}
}
<br>
<div>
<input type="checkbox" id="checkit1" /> Cash <br>
<input type="checkbox" id="checkit2" /> Square <br>
<input type="checkbox" id="checkit3" /> Paypal <br>
------------------------------------------------<br>
<input type="checkbox" id="checkit4" /> BBT <br>
<input type="checkbox" id="checkit5" /> Citi <br>
**<input type="checkbox" id="click1" /> dep <br>
**<input type="checkbox" id="click2" /> trans <br>
**<input type="checkbox" id="click3" /> check <br>
</div>
我做错了什么?
最佳答案
有多种方法可以实现此目的 - 一种方法 ( that retains your code's general structure ) 是选择您想要切换禁用的所有复选框:
var checkboxes = $("#checkit1, #checkit2, #checkit3");
然后在您的 click
处理程序中使用这些选中的复选框来确定是否有任何 :checked
像这样:
$(checkboxes).is(':checked') // Returns true is at least one checkbox in selected checkboxes checked
然后可以在您的脚本中使用这两行来实现您需要的功能,如下所示:
// Select checkboxes used to control/toggle disable of target checkboxes
var checkboxes = $("#checkit1, #checkit2, #checkit3");
checkboxes.on('click',checkStatus);
function checkStatus() {
// if at least one checkbox in selected checkboxes is checked then
// disable target checkboxes
if($(checkboxes).is(':checked'))
{
$("#click1").prop('disabled', true);
$("#click2").prop('disabled', true);
$("#click3").prop('disabled', true);
}
else{
$("#click1").prop('disabled', false);
$("#click2").prop('disabled', false);
$("#click3").prop('disabled', false);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<br>
<div>
<input type="checkbox" id="checkit1" /> Cash <br>
<input type="checkbox" id="checkit2" /> Square <br>
<input type="checkbox" id="checkit3" /> Paypal <br>
------------------------------------------------<br>
**<input type="checkbox" id="click1" /> box1 <br>
**<input type="checkbox" id="click2" /> box2 <br>
**<input type="checkbox" id="click3" /> box3 <br>
</div>
关于javascript - JQuery:如果选中另一个复选框,则禁用/启用多个复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53528805/