【问题标题】:How to make checkbox 'C' FALSE, if checkbox 'A' and checkbox 'B' is FALSE如果复选框'A'和复选框'B'为假,如何使复选框'C'为假
【发布时间】:2019-03-14 20:24:13
【问题描述】:
如果我将复选框“A”和复选框“B”从 TRUE 更改为 FALSE,我想将复选框“C”设为 FALSE。
这是我的示例代码,不知道要添加什么才能继续。
如果复选框“A”或“B”为真,我仍希望复选框“C”保持为真。
谢谢!
$(".loyalty").change(function () {
if ($(".loyalty").is(':checked')) {
$(".email_optin_status").prop('checked', true);
}
else {
$(".email_optin_status").prop('checked', false);
}
});
$(".newsletters").change(function () {
if ($(".newsletters").is(':checked')) {
$(".email_optin_status").prop('checked', true);
}
else {
$(".email_optin_status").prop('checked', false);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" class="loyalty" name="A"> A
<hr>
<input type="checkbox" class="newsletters" name="B"> B
<hr>
<input type="checkbox" class="email_optin_status" name="C"> C
【问题讨论】:
标签:
javascript
html
coffeescript
【解决方案1】:
$(".loyalty").change(function () {
if ($(".loyalty").is(':checked')) {
$(".email_optin_status").prop('checked', true);
}
else if ($(".newsletters").is(':checked')) {
$(".email_optin_status").prop('checked', true);
} else
{
$(".email_optin_status").prop('checked', false);
}
});
$(".newsletters").change(function () {
if ($(".newsletters").is(':checked')) {
$(".email_optin_status").prop('checked', true);
}
else if(($(".loyalty").is(':checked'))){
$(".email_optin_status").prop('checked', true);
}
else{
$(".email_optin_status").prop('checked', false);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" class="loyalty" name="A"> A
<hr>
<input type="checkbox" class="newsletters" name="B"> B
<hr>
<input type="checkbox" class="email_optin_status" name="C"> C
【解决方案2】:
逻辑很简单:
C.checked = A.checked || B.checked;
例如
function updateCBs(evt) {
document.querySelector('[name="C"]').checked =
document.querySelector('[name="A"]').checked ||
document.querySelector('[name="B"]').checked;
}
// Add listeners onload
document.addEventListener('DOMContentLoaded', function(){
var cbs = [
document.querySelector('[name="A"]'),
document.querySelector('[name="B"]')
];
cbs.forEach(cb => cb.addEventListener('click', updateCBs, false));
// Update checkboxes
updateCBs();
}, false);
<input type="checkbox" name="A"> A<hr>
<input type="checkbox" name="B"> B<hr>
<input type="checkbox" name="C"> C
监听器可以是一行,但它是一个很长的语句。