我想获取 html 中复选框的总数。
要求: (1) 通过Javascript (2) 我所有的复选框 ID 都是“id=idCheckBox”, (3) 每个checkbox的名字都是预留给后台使用的。不适用于javascript。 (4) 每个checkbox的名字命名方式如checkbox_1, checkbox_2,...,其中数字表示checkbox的序号。
表格 HTML
<table class="form_table" border="0" cellpadding="0" width="750px" id="idRoutineListTable">
<tr>
<td style="align:center;" class="routineListCell">
<input type='checkbox' name='checkbox_1' id='idCheckBox'></input>
<!-- It may many checkbox here.-->
</td>
</tr>
</table>
我的JS代码,功能是在删除之前检查是否选中了任何复选框。如果没有选中复选框,它会弹出警告。
function beforeDelete() /*{{{*/
{
var checked=0;
var checkboxAll=document.all["idCheckBox"];
//the error is here, when there is only one checkbox, I cannot get length value,
//coz checkboxAll is not recognized as an array. However, if there are more than
//two checkboxes, the function works.
alert (checkboxAll.length);
for(var i=0;i<checkboxAll.length;i++) {
if (checkboxAll[i].checked==true) {
checked++;
}
}
if(checked==0) {
alert('Please select the item you will delete');
return false;
}
} /*}}}*
问题已在上面的代码中指出。 有解决这个问题的想法吗?
最佳答案
这是一个使用 jQuery 的完整工作示例:
<script src="../../Scripts/jquery-1.5.1.js" type="text/javascript"></script>
<script>
function beforeDelete() {
if ($("input:checked").length == 0) {
alert('Please select the item you will delete');
return false;
}
return true;
}
</script>
<form onsubmit="return beforeDelete()">
<table class="form_table" border="0" cellpadding="0" width="750px" id="idRoutineListTable">
<tr>
<td style="align:center;" class="routineListCell">
<input type='checkbox' name='checkbox_1' id='idCheckBox'></input>
<input type='checkbox' name='checkbox_2' id='idCheckBox'></input>
<input type='checkbox' name='checkbox_3' id='idCheckBox'></input>
<!-- It may many checkbox here.-->
</td>
</tr>
</table>
<input type="submit" />
</form>
关于javascript - 如何通过 Javascript 计算表格中复选框的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6774188/