Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting total number of checked checkboxes [duplicate]

I have a form with checkboxes with the input being stored in an array:

<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>

Using jQuery I want to find how many checkboxes are ticked/checked:

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

alert(total.length);

However the total is always output a 0. What am I doing wrong?

like image 393
Alan A Avatar asked Jun 13 '13 10:06

Alan A


People also ask

How many checkbox we can check at a time?

So user can select as many checkboxes they want but sum can't exceed 10.


1 Answers

Use :checked in the selector, and don't serialize it, just get the length.

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

Also use [] in the selector, because your checkboxes use [] in the name. As @Felix Kling points out, it is part of the name and so you have to explicitly specify the [].

Demo

like image 133
MrCode Avatar answered Sep 30 '22 03:09

MrCode