javascript - 如何通过 Javascript 计算表格中复选框的数量

标签 javascript html

我想获取 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/

相关文章:

javascript - 在动画 JavaScript 和 HTML 中制作幻灯片

html - 将级联 ul 显示为内联 block 不起作用

jquery - 是否可以使用 JQuery Mobile 在辅助 div 类中包含可折叠内容?

javascript - 图像相互接触时不会触发警报

html - 在页面左侧显示第一列的 4 行

javascript - 传单标记 'dragend' 触发 'click'

javascript - 在条件运算符中运行代码是否安全?

javascript - 如何使用 HTML、CSS 和 JQuery 使菜单从移动设备的右侧滑动?

javascript - 无法从模型中发出数组中的现有属性

javascript - 想要在基于 React 的应用程序中保护 jwt