作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个表单,想知道有多少个复选框被选中了?
我的复选框 ID 将相同,event_id
和名称将是这样的:data[Noncompetitor][is_black][4]
我怎么可以?
尽快让我知道。
谢谢!
最佳答案
一旦您获得了对您的 form's element 的引用,很容易遍历元素:
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
.
例如,如果您的表单的 id
是“foo”,那么:
var checkedCount = countChecked(document.getElementById('foo'));
题外话:使用像 jQuery 这样的库可以使很多这样的东西变得很多更容易, Prototype , YUI , Closure , 或 any of several others为了消除浏览器差异,为您提供丰富的方法来通过 CSS 选择器等遍历元素。
例如,上面的代码可以用 jQuery 写成这样:
var checkedCount = $("#foo :checkbox:checked").length;
...也就是说,'找到所有选中的复选框,这些复选框是具有 id
“foo”的元素的后代',然后使用生成的 jQuery 的长度对象(jQuery 对象类似于数组)。
关于Javascript:获取总选中的复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5594882/
我是一名优秀的程序员,十分优秀!