This question already has answers here:
How do I count how many checkboxes are selected on a page with jQuery
                            
                                (4个答案)
                            
                    
                6年前关闭。
        

    

我有一个带有复选框的表单,其中输入存储在数组中:

<input type="checkbox" name="lineup[]" value="1">Tom</input>
<input type="checkbox" name="lineup[]" value="2">David</input>
<input type="checkbox" name="lineup[]" value="3">Sarah</input>


我想使用jQuery查找已勾选/选中的复选框数量:

var total=$(this).find('input[name=lineup]').serialize();

alert(total.length);


但是总数总是输出0。我在做什么错?

谢谢,

艾伦

最佳答案

在选择器中使用:checked,不要序列化它,只需获取长度即可。

var total=$(this).find('input[name="lineup[]"]:checked').length;


同时在选择器中使用[],因为您的复选框在名称中使用[]。正如@Felix Kling指出的那样,它是名称的一部分,因此您必须显式指定[]

Demo

10-01 07:27
查看更多