63

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?

dragonmantank
  • 15,243
  • 20
  • 84
  • 92

10 Answers10

141

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
});
patridge
  • 26,385
  • 18
  • 89
  • 135
  • `@` is not required in `$.each($("input[@name='user_group[]']:checked"), function() {` – IsmailS Jul 15 '10 at 07:33
  • @Ismail, it has been updated for post-1.3 jQuery. Version 1.3 was released after the answer was posted (posted Jan 06, 2009, 1.3 released Jan 14, 2009). Attribute selectors shouldn't be used by anyone using v1.3 or newer. – patridge Jul 15 '10 at 15:13
  • 1
    Can't `[name='user_group[]']` be called as attribute selector. I still use it in 1.4.2. Is there are better alternative now? – IsmailS Jul 16 '10 at 08:59
  • 1
    That was a typo on my part. Attribute selectors [with "@"] shouldn't be used by anyone using v1.3 or newer. – patridge Jul 16 '10 at 21:40
17

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.

Pat Osterday
  • 306
  • 2
  • 4
  • 1
    I believe the @ was removed in jQuery 1.3 +1 – Teej Nov 10 '09 at 09:46
  • 1
    This also works if you need to get the value of all checkboxes even if they're not selected. For example I needed to create an array (hash) with all checkboxes values (selected or not) just remove the `:checked` part – Metafaniel Jun 26 '12 at 14:43
12

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();
});
Hooloovoo13
  • 241
  • 2
  • 12
12

With map in instead of each it is possible to avoid the array creation step:

var checkedCheckboxesValues = 
    $('input:checkbox[name="groupName"]:checked')
        .map(function() {
            return $(this).val();
        }).get();

From the map() page of the docs:

Pass each element in the current matched set through a function, producing a new jQuery object containing the return values

get() turns those values into an array.

Clodoaldo Neto
  • 118,695
  • 26
  • 233
  • 260
4

mhata dzenyu mese. its actually

var selectedGroups  = new Array();
$(".user_group[checked]").each(function() {
    selectedGroups.push($(this).val());
});
Brandon
  • 68,708
  • 30
  • 194
  • 223
2

I just shortened the answer I selected a bit:

var selectedGroups  = new Array();
$("input[@name='user_group[]']:checked").each(function() {
    selectedGroups.push($(this).val());
});

and it works like a charm, thanks!

dragonmantank
  • 15,243
  • 20
  • 84
  • 92
1
var values = $("input[name='user_group']:checked").map(function(){
      return $(this).val();
    }).get();

This will give you all the values of the checked boxed in an array.

jwaern
  • 643
  • 5
  • 16
1

I'm not 100% entirely sure how you want to "grab" the values. But if you want to iterate over the checkboxes you can use .each like so:

("input[@name='user_group[]']").each( function() {
    alert($(this).val());
});

Of course a better selector is available:

$(':checkbox')
Brandon
  • 68,708
  • 30
  • 194
  • 223
Steve Davis
  • 716
  • 5
  • 13
0

You can have a javascript variable which stores the number of checkboxes that are emitted, i.e in the <head> of the page:

<script type="text/javascript">
var num_cboxes=<?php echo $number_of_checkboxes;?>;
</script>

So if there are 10 checkboxes, starting from user_group-1 to user_group-10, in the javascript code you would get their value in this way:

var values=new Array();
for (x=1; x<=num_cboxes; x++)
{
   values[x]=$("#user_group-" + x).val();
}
Ali
  • 261,656
  • 265
  • 575
  • 769
0

$(document).ready(function(){
      $('#btnskillgroup').click(function(){
              getCheckedGroups('skills');
            });
   $('#btncitiesgroup').click(function(){
              getCheckedGroups('cities');
            });
         var getCheckedGroups = function(groupname){
               var result = $('input[name="'+groupname+'"]:checked');
              if (result.length > 0) {
               var resultstring = result.length +"checkboxes checked <br>";
               result.each(function(){
                resultstring += $(this).val()+" <br>"; //append value to exsiting var
               });
       $('#div'+groupname).html(resultstring);
      }else{
       $('#div'+groupname).html(" No checkbox  is Checked");
      }
         
         };
     });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
Skills:<input type="checkbox" name="skill"  value="Java"> Java
    <input type="checkbox" name="skill" value="Jquery"> Jquery
    <input type="checkbox" name="skill" value="PHP"> PHP
<br>
<input type="checkbox" name="cities"  value="Pune"> Pune
    <input type="checkbox" name="cities" value="Baramati"> Baramati
    <input type="checkbox" name="cities" value="London"> London

    <input type="submit" id="btnskillgroup" value="Get Checked Skill group">
<input type="submit" id="btncitiesgroup" value="Get cities checked group">
    <div id="divskills"></div>
<div id="divcities"></div>
Pramod Kharade
  • 2,005
  • 1
  • 22
  • 41