Select values of checkbox group with jQuery

I'm using Zend_Form to output a set group of checkboxes:

<label style="white-space: nowrap;"><input type="checkbox" name="user_group[]" id="user_group-20" value="20">This Group</label>

With a normal HTTP Post these values are passed as an array, but when I'm somewhat stumped on how to grab all the values using jQuery. I figured I can select the group using:

$("input[@name='user_group[]']").val()

but that just grabs the value of the first checkbox in the list regardless of if it is checked of not. Any ideas?


You could use the checked selector to grab only the selected ones (negating the need to know the count or to iterate over them all yourself):

$("input[name='user_group[]']:checked")

With those checked items, you can either create a collection of those values or do something to the collection:

var values = new Array();
$.each($("input[name='user_group[]']:checked"), function() {
  values.push($(this).val());
  // or you can do something to the actual checked checkboxes by working directly with  'this'
  // something like $(this).hide() (only something useful, probably) :P
});

I'm not sure about the "@" used in the selector. At least with the latest jQuery, I had to remove the @ to get this to function with two different checkbox arrays, otherwise all checked items were selected for each array:

var items = [];
$("input[name='items[]']:checked").each(function(){items.push($(this).val());});

var about = [];
$("input[name='about[]']:checked").each(function(){about.push($(this).val());});

Now both, items and about work.


Use .map() (adapted from the example at http://api.jquery.com/map/):

var values = $("input[name='user_group[]']:checked").map(function(index,domElement) {
    return $(domElement).val();
});