如何计算表单中所有复选框(JavaScript)的 [英] how to count all check boxes in a form (Javascript)
问题描述
我有,获取动态生成的复选框数量。所以我不知道,每次得到多少复选框中产生。我需要有一些JavaScript的方法来算总数的复选框的形式。
I have number of check boxes that gets generated dynamically. So i do not know how many check boxes gets generated each time. I need to have some JavaScript ways to count the total numbers of check boxes in a form.
<input type="checkbox" value="username1" name="check[0]" id="1" /><br/>
<input type="checkbox" value="userusername2" name="check[1]" id="1" /><br/>
<input type="checkbox" value="userusername3" name="check[2]" id="1" /><br/>
我不能改变的复选框的名字,因为我需要的值发送到服务器端的PHP脚本作为一个数组。
I can not change the name of the check boxes as i need to send the values to serverside PHP script as an array.
推荐答案
由于所有其他的答案是基于jQuery,我会提供了一个纯JavaScript解决方案。假设下面的形式:
Since all other answers are jquery based, I'll offer a pure javascript solution. Assuming the following form:
<form id="myform">
<input type="checkbox" value="username1" name="check[0]" /><br/>
<input type="checkbox" value="userusername2" name="check[1]" /><br/>
<input type="checkbox" value="userusername3" name="check[2]" /><br/>
</form>
您可以计算复选框元件具有下列逻辑数:
You could compute the number of checkbox elements with the following logic:
<script type="text/javascript">
var myform = document.getElementById('myform');
var inputTags = myform.getElementsByTagName('input');
var checkboxCount = 0;
for (var i=0, length = inputTags.length; i<length; i++) {
if (inputTags[i].type == 'checkbox') {
checkboxCount++;
}
}
alert(checkboxCount);
</script>
BTW:正如其他人所指出的,在所有的HTML标签的 ID
属性应该是在文档中是唯一的。我忽略你的 ID =1
属性在我上面的示例HTML。
BTW: As others have noted, the id
attribute in any HTML tag should be unique within the document. I've omitted your id="1"
attributes in my sample HTML above.
如果您只是想计算,而无需使用包含表单元素在整个页面上的所有复选框元素,这应该工作:
If you simply want to count all checkbox elements on the entire page without using a containing form element, this should work:
<script type="text/javascript">
var inputTags = document.getElementsByTagName('input');
var checkboxCount = 0;
for (var i=0, length = inputTags.length; i<length; i++) {
if (inputTags[i].type == 'checkbox') {
checkboxCount++;
}
}
alert(checkboxCount);
</script>
这篇关于如何计算表单中所有复选框(JavaScript)的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!