检查jQuery是否选中复选框 [英] Check if checkbox is checked with jQuery

查看:93
本文介绍了检查jQuery是否选中复选框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



我使用下面的代码,但它总是返回不管ID是否为已选中复选框的数量。

 函数isCheckedById(id){
alert
var checked = $(input [@ id =+ id +]:checked)。
alert(checked);

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


解决方案

ID在您的文档中必须是唯一的,这意味着您不应执行此操作:

 < input type =checkboxname =chk []id =chk []value =Apples/> 
< input type =checkboxname =chk []id =chk []value =Bananas/>相反,删除ID,然后按名称或包含元素选择它们: p>

 < fieldset id =checkArray> 
< input type =checkboxname =chk []value =Apples/>

< input type =checkboxname =chk []value =Bananas/>
< / fieldset>

现在的jQuery:

  var atLeastOneIsChecked = $('#checkArray:checkbox:checked')。 0; 
//标识符和选择器之间不能有空格

//或者没有容器:

var atLeastOneIsChecked = $('input [name = chk []]:checked')。 0;


How can I check if a checkbox in a checkbox array is checked using the id of the checkbox array?

I am using the following code, but it always returns the count of checked checkboxes regardless of id.

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

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

解决方案

IDs must be unique in your document, meaning that you shouldn't do this:

<input type="checkbox" name="chk[]" id="chk[]" value="Apples" />
<input type="checkbox" name="chk[]" id="chk[]" value="Bananas" />

Instead, drop the ID, and then select them by name, or by a containing element:

<fieldset id="checkArray">
    <input type="checkbox" name="chk[]" value="Apples" />

    <input type="checkbox" name="chk[]" value="Bananas" />
</fieldset>

And now the jQuery:

var atLeastOneIsChecked = $('#checkArray:checkbox:checked').length > 0;
//there should be no space between identifier and selector

// or, without the container:

var atLeastOneIsChecked = $('input[name="chk[]"]:checked').length > 0;

这篇关于检查jQuery是否选中复选框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆