Get a list of checked checkboxes in a div using jQ

2019-01-03 07:47发布

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>

6条回答
在下西门庆
2楼-- · 2019-01-03 08:26

This works for me.

var selecteditems = [];

$("#Div").find("input:checked").each(function (i, ob) { 
    selecteditems.push($(ob).val());
});
查看更多
乱世女痞
3楼-- · 2019-01-03 08:27
$("#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;
});
查看更多
Fickle 薄情
4楼-- · 2019-01-03 08:31

Would this do?

var selected = [];
$('div#checkboxes input[type=checkbox]').each(function() {
   if ($(this).is(":checked")) {
       selected.push($(this).attr('name'));
   }
});
查看更多
Evening l夕情丶
5楼-- · 2019-01-03 08:33

Combination of two previous answers:

var selected = [];
$('#checkboxes input:checked').each(function() {
    selected.push($(this).attr('name'));
});
查看更多
beautiful°
6楼-- · 2019-01-03 08:38

I needed the count of all checkboxes which are checked. Instead of writing a loop i did this

$(".myCheckBoxClass:checked").length;

Compare it with the total number of checkboxes to see if they are equal. Hope it will help someone

查看更多
做自己的国王
7楼-- · 2019-01-03 08:43

You could also give them all the same name so they are an array, but give them different values:

<div id="checkboxes">
    <input type="checkbox" name="c_n[]" value="c_n_0" checked="checked" />Option 1
    <input type="checkbox" name="c_n[]" value="c_n_1" />Option 2
    <input type="checkbox" name="c_n[]" value="c_n_2" />Option 3
    <input type="checkbox" name="c_n[]" value="c_n_3" checked="checked" />Option 4
</div>

You can then get only the value of only the ticked ones using map:

$('#checkboxes input:checked[name="c_n[]"]')
            .map(function () { return $(this).val(); }).get()
查看更多
登录 后发表回答