gpt4 book ai didi

Javascript:获取总选中的复选框

转载 作者:行者123 更新时间:2023-11-29 18:33:19 25 4
gpt4 key购买 nike

我有一个表单,想知道有多少个复选框被选中了?

我的复选框 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com