1

I have many checkboxes on a page, like this:

<input type="checkbox"  id="cb_31" class="observedType1">
<input type="checkbox"  id="cb_32" class="observedType1" checked="checked">
<input type="checkbox"  id="cb_33" class="observedType1">
<input type="checkbox"  id="cb_40" class="observedType2" checked="checked">

I then wanted to retrieve the classes of all checked boxes in an array (ideally as a list of unique items), so I'm looking to for ['observedType1'l'observedType2'].
My best idea was: var clss=$("[class*='observedType']:checked").attr("class"); but that only gives me a string "observedType1".

How can I get the array I am looking for? (or a "list" to walk through in a loop)...

There's also a fiddle

MBaas
  • 7,248
  • 6
  • 44
  • 61

2 Answers2

3

You need to iterate all the :checked checkboxes, here you can use .map()

var clss=$("[class*='observedType']:checked").map(function(){
   return $(this).attr('class')
}).get();

Updated Fiddle


I would recommend you to use custom data-* prefix custom attribute to store the arbitrary data.

<input type="checkbox" id="cb_31" class="observedType" data-type="observedType1">

Which can be retrieved using .data() method

var clss = $(".observedType:checked").map(function() {
  return $(this).data('type')
}).get();

With Custom attribute Fiddle

Satpal
  • 132,252
  • 13
  • 159
  • 168
1

you can do the following in javascript :

var myInputs = document.getElementsByTagName('input');
var myCheckedInputs = Array.from(myInputs).filter(function(input) {
  return input.checked;
});
boehm_s
  • 5,254
  • 4
  • 30
  • 44