1

I want to collect checked checkboxes (values) with a classname and put them into an array. Just like that one:

var a = new Array();
$('.categoriesCb').each(function(i, item) {
  if ($(item).prop('checked'))
  {
    a.push($(item).val());
  }
  alert(JSON.stringify(a));
});

my problem is its a bit big. Cant it be done with one-line?11

John Smith
  • 6,129
  • 12
  • 68
  • 123

4 Answers4

1

You can use .map() function along with .get(). You can also eliminate paramete item and use context this:

var a = $('.categoriesCb:checked').map(function(){
  return $(this).val();
}).get();
Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125
1

Use jQuery.map()

$('.categoriesCb:checked').map(function() {
  return this.value;
}).get();
Rayon
  • 36,219
  • 4
  • 49
  • 76
1

another way is to use jQuery.makeArray() with .map():

var arr = jQuery.makeArray($(':checked').map(function(){ return this.value; }));

$('pre').html(JSON.stringify(arr));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" checked name="options" value="1" />
<input type="checkbox" name="options" value="2" />
<input type="checkbox" name="options" value="3" />
<input type="checkbox" checked name="options" value="4" />
<input type="checkbox" checked name="options" value="5" />

<br>
<pre></pre>
Jai
  • 74,255
  • 12
  • 74
  • 103
1

Just a pure JS single liner. Note that node list to array conversion with the spread operator works fine in Firefox but with Chrome it's only possible with v51 on. Otherwise you will have to go with the good old Array.prototype.map.call(document.querySelectorAll("input[type=checkbox][checked]"), e => e.value) method.

var arr = [...document.querySelectorAll("input[type=checkbox][checked]")].map(e => e.value);

console.log(JSON.stringify(arr));
<input type="checkbox" checked name="options" value="1" />
<input type="checkbox" name="options" value="2" />
<input type="checkbox" name="options" value="3" />
<input type="checkbox" checked name="options" value="4" />
<input type="checkbox" checked name="options" value="5" />
Redu
  • 25,060
  • 6
  • 56
  • 76