我有一个动态的复选框列表,所有复选框都具有相同的类。我想禁用提交按钮,直到选择了“group1”类中的所有复选框。
我也只想在此类出现在页面上时执行此操作。 我是这样做的:
<input type="checkbox" class="group1" value="20" />
<input type="checkbox" class="group1" value="15" />
<input type="checkbox" class="group1" value="14" />
if ($(".group1").length > 0) {
//run below code
}
所以我开始这样,但不确定如何知道什么时候该类的所有复选框都被选中。
$(document).ready(function() {
$(':input[type="submit"]').prop('disabled', true);
$('input[type="text"]').keyup(function() {
var checkboxes = $('.group1');
if($(this).is(':checked')) {
//if all chekced, enable submit button
$(':input[type="submit"]').prop('disabled', false);
} else {
$(':input[type="submit"]').prop('disabled', true);
}
}
});
});
我看过这个jQuery Array of all selected checkboxes (by class) ,但由于类可以是任意长度,我不知道如何检查是否所有类都被选中。
最佳答案
最简单的方法是将复选框总数与已选中的数量进行比较,如下所示:
var $group = $('.group1');
$(':input[type="submit"]').prop('disabled', $group.length != $group.filter(':checked').length);
关于javascript - 按类别分类的复选框全部选中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45588478/