Javascript:获取总复选框 [英] Javascript: get total checked checkboxes
问题描述
我有一个表单,想要查找,已选中多少个复选框?
I have a form and want to find, how many checkboxes have been checked?
我的复选框ID将是相同的, event_id
和名称将是这样的:
data [Noncompetitor] [is_black] [4]
My Checkbox id will be same, event_id
and name will be something like this: data[Noncompetitor][is_black][4]
我如何?
请尽快通知我。
谢谢!
推荐答案
一旦您参考了表单的元素,很容易循环遍历元素:
Once you have a reference to your form's element, it's easy to loop through the elements:
function countChecked(form) {
var index, element;
for (index = 0; index < form.elements.length; ++index) {
element = form.elements[index];
// You may want to check `element.name` here as well
if (element.type.toUpperCase() == "CHECKBOX" && element.checked) {
++checked;
}
}
return checked;
}
有很多方法可以引用表单元素。例如,给出表单 id
,并使用 document.getElementById
。
There are lots of ways to get a reference to the form element. For instance, give the form an id
and use document.getElementById
.
因此,如果您的表单的 id
是foo,则:
So if your form's id
is "foo", for instance, then:
var checkedCount = countChecked(document.getElementById('foo'));
:使用 jQuery ,这样的图书馆,您可以更轻松地很多 href =http://prototypejs.org =nofollow> Prototype , YUI ,关闭或任何其他几个人来平滑浏览器差异,给你丰富的方式通过CSS选择器遍历元素等。
Off-topic: A lot of this stuff can be made a lot easier using a library like jQuery, Prototype, YUI, Closure, or any of several others to smooth over browser differences, give you rich ways to traverse to elements via CSS selectors, and such.
例如,上面的代码可以使用jQuery写成:
For example, the above can be written using jQuery like this:
var checkedCount = $("#foo :checkbox:checked").length;
...这说明:找到所有选中的复选框是elemen twith的后代 id
foo'然后使用生成的jQuery对象的长度(jQuery对象是数组类型)。
...which says, 'find all checked checkboxes that are descendants of the elemen twith the id
"foo"' and then uses the length of the resulting jQuery object (jQuery objects are array-like).
这篇关于Javascript:获取总复选框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!