如何使用复选框数组的id检查复选框数组中的复选框是否选中?

我正在使用以下代码,但它总是返回选中复选框的计数,而不管id如何。

function isCheckedById(id) {
    alert(id);
    var checked = $("input[@id=" + id + "]:checked").length;
    alert(checked);

    if (checked == 0) {
        return false;
    } else {
        return true;
    }
}

当前回答

您可以使用此代码,

if($("#checkboxId").is(':checked')){
     // Code in the case checkbox is checked.
} else {
     // Code in the case checkbox is NOT checked.
}

其他回答

您可以使用此代码,

if($("#checkboxId").is(':checked')){
     // Code in the case checkbox is checked.
} else {
     // Code in the case checkbox is NOT checked.
}

在我的示例中,情况是一个对话框,然后在关闭对话框之前验证复选框。以上都没有,如何检查jQuery中是否选中了复选框?如果选中复选框,jQuery似乎也不起作用。

最后

<input class="cb" id="rd" type="checkbox">
<input class="cb" id="fd" type="checkbox">

var fd=$('.cb#fd').is(':checked');
var rd= $('.cb#rd').is(':checked');

这是因为先调用类,然后调用ID,而不仅仅是ID。这可能是由于此页面上的嵌套DOM元素导致的问题。解决方法如上所述。

选中切换复选框

$("#checkall").click(function(){
    $("input:checkbox").prop( 'checked',$(this).is(":checked") );
})
$(document).on('click','#checkBoxId',function(){
  var isChecked = $(this).is(':checked');
  console.log(isChecked);
});

上面的代码也适用于引导模式。isChecked为true或flase;

使用此代码,您可以在不同的复选框组或多个复选框中检查是否选中了至少一个复选框。使用此选项,您不需要删除ID或动态ID。此代码使用相同的ID。

参考链接

<label class="control-label col-sm-4">Check Box 2</label>
    <input type="checkbox" name="checkbox2" id="checkbox21" value=ck1 /> ck1<br />
    <input type="checkbox" name="checkbox2" id="checkbox22" value=ck2 /> ck2<br />

<label class="control-label col-sm-4">Check Box 3</label>
    <input type="checkbox" name="checkbox3" id="checkbox31" value=ck3 /> ck3<br />
    <input type="checkbox" name="checkbox3" id="checkbox32" value=ck4 /> ck4<br />

<script>
function checkFormData() {
    if (!$('input[name=checkbox2]:checked').length > 0) {
        document.getElementById("errMessage").innerHTML = "Check Box 2 can not be null";
        return false;
    }
    if (!$('input[name=checkbox3]:checked').length > 0) {
        document.getElementById("errMessage").innerHTML = "Check Box 3 can not be null";
        return false;
    }
    alert("Success");
    return true;
}
</script>