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

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

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

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

当前回答

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

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

其他回答

根据jQuery文档,有以下方法可以检查是否选中了复选框。让我们考虑一个复选框(检查所有示例的工作jsfiddle)

<input type="checkbox" name="mycheckbox" id="mycheckbox" />
<br><br>
<input type="button" id="test-with-checked" value="Test with checked" />
<input type="button" id="test-with-is" value="Test with is" />
<input type="button" id="test-with-prop" value="Test with prop" />

示例1-选中

$("#test-with-checked").on("click", function(){
    if(mycheckbox.checked) {
        alert("Checkbox is checked.");
    } else {
        alert("Checkbox is unchecked.");
    }
}); 

示例2-如果jQuery为,注意-:已选中

var check;
$("#test-with-is").on("click", function(){
    check = $("#mycheckbox").is(":checked");
    if(check) {
        alert("Checkbox is checked.");
    } else {
        alert("Checkbox is unchecked.");
    }
}); 

示例3-使用jQuery属性

var check;
$("#test-with-prop").on("click", function(){
    check = $("#mycheckbox").prop("checked");
    if(check) {
         alert("Checkbox is checked.");
    } else {
        alert("Checkbox is unchecked.");
    }
}); 

检查工作jsfiddle

对于带有id的复选框

<input id="id_input_checkbox13" type="checkbox"></input>

你可以简单地

$("#id_input_checkbox13").prop('checked')

您将获得true或false作为上述语法的返回值。您可以在if子句中将其用作普通布尔表达式。

由于现在是2019年年中,jQuery有时会比VueJS、React等产品逊色。这里有一个纯粹的Javascript加载监听器选项:

<script>
  // Replace 'admincheckbox' both variable and ID with whatever suits.

  window.onload = function() {
    const admincheckbox = document.getElementById("admincheckbox");
    admincheckbox.addEventListener('click', function() {
      if(admincheckbox.checked){
        alert('Checked');
      } else {
        alert('Unchecked');
      }
    });
  }
</script>

这也是我经常使用的一个想法:

var active = $('#modal-check-visible').prop("checked") ? 1 : 0 ;

如果勾选,则返回1;否则将返回0。

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

以下所有方法都是可行的

elem.checked 

$(elem).prop("checked") 

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