bard bard - 3 months ago 24
Javascript Question

Getting list of checked checkbox values using ES6 arrow function

My checkboxes look like this:

<input type="checkbox" value="abc" checked>
<input type="checkbox" value="def" checked>

I know I can get all the values with

$('input[type=checkbox]:checked').map(function() { return $(this).val(); }).get();

The ES6 equivalent using arrow functions I thought would be something like

$('input[type=checkbox]:checked').map((el) => el.value).get();

but all I get is an empty array.



JQuery's .map() method passes a reference to the element in your callback's second argument. The first argument is an index.

You get an empty array because .value is undefined for the indices (numbers), and when you return undefined jQuery's .map() doesn't add an element to the result.


$('input[type=checkbox]:checked').map((i, el) => el.value).get();

(So the problem wasn't because you used an arrow function rather than a standard function.)