[javascript] 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?

This question is related to javascript jquery

The answer is


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


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.


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();
}

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!


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.


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.


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!


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

mhata dzenyu mese. its actually

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

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!


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();
}

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!


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


mhata dzenyu mese. its actually

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

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.


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();
});

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();
}

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.


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();
});

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

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.


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

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();
}