Get a List of Checked Checkboxes in a Div Using jQuery

Quick Summary
- Match #checkboxes input:checked with jQuery, loop over the results with .each() and push each checkbox's name or value into an array.
- Keep only one of the two push() lines, name or value, since using both adds every checkbox twice.
- The :checked selector reflects the current state, so run the code in a click or submit handler; on WordPress, use jQuery instead of $.
To find out which checkboxes a user has ticked inside a specific container, use jQuery’s :checked selector and collect the results into an array. That’s useful before you send the selection with AJAX or show it somewhere else on the page.
Example HTML
Four checkboxes inside a div with the ID checkboxes; three of them start checked.
<div id="checkboxes">
<input id="chkbx_0" type="checkbox" value="c_n_0" name="c_n_0" checked="checked" />Option 1
<input id="chkbx_1" type="checkbox" value="c_n_1" name="c_n_1" checked="checked" />Option 2
<input id="chkbx_2" type="checkbox" value="c_n_2" name="c_n_2" />Option 3
<input id="chkbx_3" type="checkbox" value="c_n_3" name="c_n_3" checked="checked" />Option 4
</div>The jQuery
var selected = [];
$('#checkboxes input:checked').each(function() {
selected.push($(this).attr('name'));
//OR
selected.push($(this).attr('value'));
});#checkboxes input:checkedmatches only the checked inputs inside that div. Change the ID to match your container..each()loops over them, andpush()adds each one to theselectedarray.- The two
push()lines are alternatives, as the//ORcomment says: keep the one that readsnameor the one that readsvalue. With both, every checkbox is added twice. With one line and the HTML above, the result is["c_n_0", "c_n_1", "c_n_3"]. :checkedreflects the current state, not only the initialcheckedattribute. Run the code when you need the list, for example in a button’s click handler or when the form is submitted.
On WordPress, jQuery runs in no-conflict mode, so use jQuery instead of $, or wrap the code in jQuery(function ($) { … }). Otherwise the script stops with TypeError: $ is not a function.
Related articles
- getting a single input’s value in plain JavaScript: when you only need one field
