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

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

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

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

当前回答

对于带有id的复选框

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

你可以简单地

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

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

其他回答

试试这个。。。

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

以下所有方法都很有用:

$('#checkbox').is(":checked")

$('#checkbox').prop('checked')

$('#checkbox')[0].checked

$('#checkbox').get(0).checked

建议避免使用DOMement或内联“this.checked”,而应使用jQuery on方法作为事件侦听器。

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

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

实际上,根据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;