views:

510

answers:

3

I want to get a list of names of checkboxes that are selected in a div with certain id. How would I do that using jQuery?

E.g., for this div I want to get array ["c_n_0"; "c_n_3"] or a string "c_n_0;c_n_3"

<div id="checkboxes">
    <input id="chkbx_0" type="checkbox" name="c_n_0" checked="checked" />Option 1
    <input id="chkbx_1" type="checkbox" name="c_n_1" />Option 2
    <input id="chkbx_2" type="checkbox" name="c_n_2" />Option 3
    <input id="chkbx_3" type="checkbox" name="c_n_3" checked="checked" />Option 4
</div>
+1  A: 

Would this do?

var selected = [];
$('div#checkboxes input[type=checkbox]').each(function() {
   if ($(this).checked) {
       selected.push($(this).attr('name'));
   }
});
nikc
+4  A: 
$("#checkboxes").children("input:checked")

will give you an array of the elements themselves. If you just specifically need the names:

$("#checkboxes").children("input:checked").map(function() {
    return this.name;
});
Corey
I think that should be return this.name or return $(this).attr('name');
Jansen Price
`$("#checkboxes :checked").map(...)` would be more concise. As Jansen points out, it should be `$(this).attr("name")`; but I would consider a simple `this.name` which should be just as compatible.
Alex Barrett
yeah, you're right, this.name would be better
Corey
+4  A: 

Combination of two previous answers:

var selected = new Array();
$('#checkboxes input:checked').each(function() {
    selected.push($(this).attr('name'));
});
Alex LE