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

1
  • you almost got it you just need to iterate on all the checked checkbox Commented May 4, 2017 at 11:08

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

2 Comments

Cool stuff - thanks! Especially for data-* !
Updated your fiddle so that actually works with the custom-attribute AND added unique...
1

you can do the following in javascript :

var myInputs = document.getElementsByTagName('input');
var myCheckedInputs = Array.from(myInputs).filter(function(input) {
  return input.checked;
});

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.