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

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

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

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

当前回答

关于选中的属性,最重要的概念是它与所检查的属性不对应。属性实际上对应于defaultChecked属性,应使用仅设置复选框的初始值。选中的属性值不会随复选框的状态而改变,而已检查属性。因此,跨浏览器兼容的方式确定是否选中复选框以使用该属性

以下所有方法都是可行的

elem.checked 

$(elem).prop("checked") 

$(elem).is(":checked") 

其他回答

实际上,根据jsperf.com的说法,DOM操作最快,然后是$().prp(),然后是$().is()!!

以下是语法:

var checkbox = $('#'+id);
/* OR var checkbox = $("input[name=checkbox1]"); whichever is best */

/* The DOM way - The fastest */
if(checkbox[0].checked == true)
   alert('Checkbox is checked!!');

/* Using jQuery .prop() - The second fastest */
if(checkbox.prop('checked') == true)
   alert('Checkbox is checked!!');

/* Using jQuery .is() - The slowest in the lot */
if(checkbox.is(':checked') == true)
   alert('Checkbox is checked!!');

我个人更喜欢.prop()。与.is()不同,它也可以用来设置值。

$('#' + id).is(":checked")

如果选中该复选框,则会出现这种情况。

对于具有相同名称的复选框数组,您可以通过以下方式获得选中复选框列表:

var $boxes = $('input[name=thename]:checked');

然后,要循环浏览它们并查看检查内容,您可以执行以下操作:

$boxes.each(function(){
    // Do stuff here with this
});

要查找检查的数量,您可以执行以下操作:

$boxes.length;
$(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>

试试这个。。。

$(function(){
  $('body').on('click','.checkbox',function(e){
    
    if($(this).is(':checked')){
      console.log('Checked')
    } else {
      console.log('Unchecked')
    }
  })
})