[英]How to add remove class on button if atleast one checkbox is checked
如果至少选中一个复选框,我正在尝试在按钮上添加/删除 class,从复选框列表中,HTML 是这样的
<button class="add-tag disabled"></button>
<button class="remove-tag disabled"></button>
<table id="product_table">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
</table>
JQuery
$(document).on('change','#product_table input:checkbox' , function(){
if($(this).is(":checked")) {
$('.add-tag').removeClass("disabled");
$('.remove-tag').removeClass("disabled");
console.log('got checked');
} else {
$('.add-tag').addClass("disabled");
$('.remove-tag').addClass("disabled");
console.log('got unchecked');
}
});
});
if($(this).is(":checked")) {
此行正在检查刚刚更改的复选框是否被选中。 当你真的需要检查它们中的任何一个是否被检查时。
if ($('#product_table input:checkbox:checked').length)
检查是否存在已检查的内容将导致仅在未检查任何内容时才添加 class。
第一个问题是使用input
作为table
标签的后代。 由于某种原因 jQuery 不读取它们。 然后,在您的事件中,您正在检查输入是否正在切换,而不是如果检查了至少输入。
请参阅此代码:
$(document).on('change', '#product_table input:checkbox', function() { // Check how many input checked const checked = $("#product_table input:checkbox:checked").length; if (checked > 0) { $('.add-tag').removeClass("disabled"); $('.remove-tag').removeClass("disabled"); console.log('got checked'); } else { $('.add-tag').addClass("disabled"); $('.remove-tag').addClass("disabled"); console.log('got unchecked'); } });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button class="add-tag disabled">Add Tag</button> <button class="remove-tag disabled">Remove Tag</button> <div id="product_table"> <input type="checkbox"> <input type="checkbox"> <input type="checkbox"> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.