0

我有一个表格,它使用 php while 循环显示表格中的名称列表,每个名称旁边都有一个复选框,以便用户可以选择 2 个名称在下一页上并排显示。

我正在使用 jquery 表单验证器,如果在进入下一页之前选择了多于或少于 2 个名称,我希望它显示一条消息。验证适用于简单的事情,如直接的字符串比较等,但我无法使用它,我怀疑这是因为我试图获取选中的复选框数量的方式。

这是表格...

 <form method="post" onsubmit="return validation()" action="merge_accounts.php"
       name="merge_form" id="merge_form" >
   <table>
       <?php while ($row = mysqli_fetch_array($sql)){
                $account_id = $row['id']; ?>
            <tr>
                <td><input type="checkbox" id="merge[]" name="merge[]"  value="<? echo $row['id']; ?>" style="margin-left:10px" /></td>
                <td class="results_cell" style="padding-left:0px">
                    <a title="<? $row['name']; ?>" href="account_info.php?id=<? echo $account_id; ?>" onClick="this.document.id.submit();"><? 
                    if(strlen($row['name']) > 45){
                        echo substr($row['name'], 0, 45).'...'; 
                    } else {
                        echo $row['name'];
                    }?></a>
                </td>
            </tr>
            <tr>
                <td colspan="2" class="no_hover">
                  <input type="submit" class="advanced_buttons"
                   style="margin: 0px 5px 3px 10px; height:30px; width:60px" 
                   name="merge_submit" value="Merge" />
               </td>
           </tr>
      </table>
 </form>

jQuery...

<script>

    function validation()
    {
        var num = document.forms["merge_form"]["merge"].length;
            if(num != 2)
            {
                $.msgbox("Please select 2 items", {type:"info",
                    buttons: [
                        {type: "submit", value: "OK"}
                    ]
                });
                return false;
            }
    }

</script>

目前,表单只是忽略验证功能并提交,无论勾选多少个复选框

4

2 回答 2

7

要查找选中复选框的数量:

var checked = $('#merge_form input[type=checkbox]:checked').length;

参考:

于 2013-06-18T10:23:16.680 回答
3

试试看:

$("#merge_form input:checked").length
于 2013-06-18T10:23:56.863 回答