In the web application I'm currently working on there are a lot of places where I have many HTML checkboxes that I need to turn into a JS array of selected items. For example:
<input type="checkbox" class="example" data-item="3">
<input type="checkbox" class="example" data-item="5">
<input type="checkbox" class="example" data-item="7">
<input type="checkbox" class="example" data-item="11">
Then I have a lot of logic like this to pack the selected values into an array:
var items = [];
$('.example[data-item]:checked').each(function (_, e) {
items.push(Number($(e).data('item')));
});
My question is just this: Is there some nice way to do this in a one-liner (jQuery is allowed if needed), e.g.:
var items = /* magic */;
I realize I could write a function for this, and I will if there is no way to do it clearly otherwise, but I'm looking for some built-in JS magic that can do it all at once.
For completeness here's a snippet:
$('#button').click(function () {
var items = [];
$('.example[data-item]:checked').each(function (_, e) {
items.push(Number($(e).data('item')));
});
alert(JSON.stringify(items));
});
label { display: flex; align-items: center; }
div { display: inline-flex; flex-direction: column; }
button { margin: 1ex; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<label><input type="checkbox" class="example" data-item="3"> Item 3</label>
<label><input type="checkbox" class="example" data-item="5"> Item 5</label>
<label><input type="checkbox" class="example" data-item="7"> Item 7</label>
<label><input type="checkbox" class="example" data-item="11"> Item 11</label>
<label><input type="checkbox" class="example" data-item="13"> Item 13</label>
<label><input type="checkbox" class="example" data-item="17"> Item 17</label>
<label><input type="checkbox" class="example" data-item="19"> Item 19</label>
<button id="button">Click Me</button>
</div>