jquery - 如果选中任何其他复选框,请取消选择特定复选框
问题描述
我有一个客户的最后一分钟请求将表单元素更改为多项选择......所以我将它们更改为复选框,一切都很好。现在复选框是动态生成的,它们之间的唯一一致性是包含“以上都不是”的复选框,现在我有以下内容:
$('input[type=checkbox]').change(function () {
if (this.parentNode.innerHTML.indexOf("None of the above") >= 0) {
console.log("Is none of the above")
if (this.checked) {
console.log("is checked")
$(this).closest('.js-form')
.find('input[type=checkbox]').not(this)
.prop('checked', false);
}
}
这在一定程度上有效,如果有人选择复选框然后选择“以上都不是”,它会清除其他选择。
我的问题只是我想要一个 else:即,如果您没有选择以上任何一项,我想要您所做的任何选择都将上述复选框中的任何一项标记为选中,false。
如果复选框不等于“以上都不是”复选框,则将“以上都不是”复选框标记为选中,false。
到目前为止,我似乎通过上述代码的变体来促进的是取消选中所有复选框
解决方案
你几乎在那里,但是你将香草与 jQuery 混合在一起,虽然这很好,但它可能会让人感到困惑 - jquery 允许你$(this)
在他们的事件侦听器中使用,所以你尝试了,this
但它在这里不一样。因此,如果不仅仅是为了一致性和可读性,最好尝试并坚持使用其中一种
如果任何其他复选框被选中,我还添加了取消选择“以上都不是”的位。
$('input[type=checkbox]').change(function() {
if ($(this).parent().text().trim().toLowerCase() === "none of the above") {
console.log("Is none of the above")
if ($(this).prop('checked')) {
console.log("is checked")
$(this).closest('.js-form')
.find('input[type=checkbox]').not(this)
.prop('checked', false);
}
} else {
$(this).closest('.js-form')
.find('input[type=checkbox]').each(function() {
if ($(this).parent().text().trim().toLowerCase() === "none of the above") $(this).prop('checked', false)
})
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='container'>
<div class='js-form'>
<label><input type='checkbox' /> Checkbox 1</label>
<label><input type='checkbox' /> Checkbox 2</label>
<label><input type='checkbox' /> Checkbox 3</label>
<label><input type='checkbox' /> Checkbox 4</label>
<hr>
<label><input type='checkbox' />None of the above</label>
</div>
推荐阅读
- python - 如何使用 OpenCV 从缓冲区读取图像?
- blazor-server-side - Blazor - 如何在不使用 Javascript 的情况下触发 OnClickEvent
- python - OpenCV:如何从黑白图像的特定部分删除文本
- python - 用 for 循环替换 divmod() 以获得商和余数
- typescript - 如何在打字稿中使用外部方法/函数检查定义的变量
- azure-functions - Azure Cosmos DB 更改源功能未触发
- reactjs - useEffect 依赖触发器如何在反应中工作?
- composer-php - 安装失败 - 尝试使用 composer 在 Drupal8 上安装模块
- javascript - 即使没有人脸,expo FaceDetector 也会在“准确”模式下继续触发“onFacesDetected”事件
- java - 分配给另一个变量的变量是否改变(原始变量改变)第二个变量是否改变?