如何使用 jQuery 查看是否选中了所有复选框

How to see if any of all checkboxes are checked using jQuery

我用循环 JSTL 创建了 8 个复选框和 1 个按钮

<c:forEach begin="1" end="8" varStatus="loop">
        <input type="checkbox" onchange = "x()" id="seat${loop.index}" name="seat${loop.index}" value="seat${loop.index}">
        <label for="seat${loop.index}">Seat${loop.index}</label>
</c:forEach>
<input type="submit" value="Save" name="savebtn">

我想检查是否选中了任何复选框,如果选中 none 则按钮将被禁用

我知道如何检查复选框是否被选中,我知道如何禁用按钮。但是,我不知道如何用循环实现它,因为我以前没有使用过 JQUERY 。这是我尝试做的。

<script>
function x() {
    for (var i = 1; i <= 8; i++){
        if ($(seat+i).prop('checked')){
            alert("+1")
        }
        else{
            alert("-1")
        }
    }
}
</script>

这段代码只检查我的第一个座位是否被选中而忽略其余的。 P.S:必须使用 JSTL 初始化复选框

您的代码只检查第一个座位是否被选中而忽略其余的,因为要选中所有复选框,您需要遍历所有复选框,而您在此处没有这样做。

var count = 0;
$($('input[type="checkbox"]')).click(function(){
  if($(this).prop('checked')){
    console.log("Checkbox is checked.");
    count++;
  }
  else{
    console.log("Checkbox " + index + " is not checked.");
    count--;
  }
);

//Disable button if no checkbox is checked.
if(count == 0){
  $('input[type="submit"]').prop('disabled', true);
}
else{
  $('input[type="submit"]').prop('disabled', false);
}
});

希望对您有所帮助。

您可以简单地使用 jQuery 的以下位,这基本上归结为 selector to get (all) checked checkboxes:

$("input[type=checkbox]:checked").length === 0

如果您的表单中碰巧有其他复选框,请输入 class:

<input type="checkbox" class="seat" ... />
$("input.seats[type=checkbox]:checked").length === 0

可以使用以下方法设置提交按钮的禁用状态:

$("input[type=submit]").prop("disabled", disabled);

其中 disabled 是布尔值。

了解这一点,您可以使用它来设置提交按钮禁用状态,例如:

$("input[type=submit]").prop("disabled", $("input[type=checkbox]:checked").length === 0);