jQuery 如何获取选中的复选框数组javascript的长度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15110437/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 14:23:18  来源:igfitidea点击:

How can get length on checked checkbox array javascript

javascriptjquerycheckbox

提问by user1148875

<form name='form1' >
   <input type=checkbox name='cbox[]' />
</form>

<script>    
   var checkbox = document.getElementsByName('ckbox[]')
   var ln = checkbox.length
   alert(ln)
</script>

How can I count only the checked checkboxes with JavaScript or jQuery?

如何只计算 JavaScript 或 jQuery 选中的复选框?

回答by Adil

Doing it with jQuery would shorten the code and make it more readable, maintainable and easier to understand. Use attribute selectorwith :checkedselector

使用 jQuery 来做这件事会缩短代码并使其更具可读性、可维护性和更容易理解。将属性选择器:checked选择一起使用

Live Demo

现场演示

$('[name="cbox[]"]:checked').length

回答by Sandeep

If you want to use plain javascript

如果你想使用普通的 javascript

var checkbox = document.getElementsByName('ckbox[]');
var ln = 0;
for(var i=0; i< checkbox.length; i++) {
    if(checkbox[i].checked)
        ln++
}
alert(ln)

回答by VisioN

jQuery solution:

jQuery 解决方案:

var len = $("[name='cbox[]']:checked").length;

JavaScript solution:

JavaScript 解决方案:

var len = [].slice.call(document.querySelectorAll("[name='cbox[]']"))
    .filter(function(e) { return e.checked; }).length;

回答by Greg

$('input:checked').lengthwill do if you do not have any other input tags than in this form.

$('input:checked').length如果您没有此表单之外的任何其他输入标签,就会这样做。

回答by Greg

Try this

尝试这个

jQuery solution:

jQuery 解决方案:

var len = $(":checked",$("input[name='cbox[]']")).size();

回答by Gaurav

var fobj = document.forms[0];

var c = 0;
for (var i = 0; i < formobj.elements.length; i++)
{
if (fobj.elements[i].type == "checkbox")
{
if (fobj.elements[i].checked)
{
c++;
}
}       
}

alert('Total Checked = ' + c);

回答by Swarne27

Try out,

试用,

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

find how many are checked,

找出有多少被检查,

$(boxes).size();

or

或者

$(boxes).length();

回答by user3089154

var len = $("[name='cbox[]']:checked").length;

will work but will not work if you are directly comparing like

会工作,但如果你直接比较就不会工作

if ( $("[name='cbox[]']").length= $("[name='cbox[]']:checked").length)

回答by Affan

you also do by this

你也这样做

you have to define class for checkBox and then follow below

您必须为 checkBox 定义类,然后按照下面的操作

var chkLength = $('input.className:checked').length; alert(chkLength);

var chkLength = $('input.className:checked').length; 警报(chkLength);

this will print your total no of checkboxes from list

这将从列表中打印您的复选框总数

回答by Nikunj K.

You may use as below as well

您也可以使用如下

$('[name=cbox\[\]]:checked').length