Getting amount of checkboxes checked by name
Asked Answered
R

4

2

I'm trying to find out how many checkboxes have been checked but am having some trouble..

My checkboxes are all named delete[].

var count = ($('#form_store_setup input[name=delete]:checked').length);

...and this doesn't work at all:

var count = ($('#form_store_setup input[name=delete[]]:checked').length);
Rutland answered 22/5, 2014 at 16:8 Comment(1)
just wrap delete[] in double quotes in your second example like var count = ($('#form_store_setup input[name="delete[]"]:checked').length);Kelcie
K
3

Simply wrap delete[] in double quotes in your second example like this:

var count = ($('#form_store_setup input[name="delete[]"]:checked').length);
Kelcie answered 22/5, 2014 at 16:14 Comment(0)
L
5

You need to escape the square brackets. Try this:

var count = $('#form_store_setup input[name=delete\\[\\]]:checked').length;

Or put the attribute value in quotes:

var count = $('#form_store_setup input[name="delete[]"]:checked').length;
Laurenelaurens answered 22/5, 2014 at 16:10 Comment(1)
or var count = ($('#form_store_setup input[name="delete[]"]:checked').length); ?Kelcie
K
3

Simply wrap delete[] in double quotes in your second example like this:

var count = ($('#form_store_setup input[name="delete[]"]:checked').length);
Kelcie answered 22/5, 2014 at 16:14 Comment(0)
G
1

Assuming you do not have any other named items, that begin with delete, you can use the "starts with" matching:

var count = ($('#form_store_setup input[name^=delete]:checked').length);
Gwenore answered 22/5, 2014 at 16:10 Comment(4)
what if a checkbox has a name for example delete_this :/Kelcie
Just a suggestion, it does depend on what else is on the page... Bit puzzled why they have delete[] in the first place :) Updated answer to qualify usage only if no other delete... elements present.Gwenore
@TrueBlueAussie it's used in PHP to send a group of element values as an array.Laurenelaurens
@Rory McCrossan: Ah, MVC does similar, but you get the index value as well in the brackets.Gwenore
F
0

This should do the trick. Try adding single quotes around your input name. Also you can call .size() instead of .length for the same effect.

var count = ($('#form_store_setup input[name='delete[]']:checked').length);

See this document for reference regarding the size() function (http://api.jquery.com/size/)

Frig answered 22/5, 2014 at 16:14 Comment(1)
Single quotes inside single quotes... busted! :)Gwenore

© 2022 - 2024 — McMap. All rights reserved.