0

Quick and dirty. I want check if all children checkbox are checked, so I would convert

$(this).parent().find(':checkbox').is(':checked')

into boolean array, in order to check it in a if condition with every() method. I have tryied every(),toArray(),makeArray and any combination fo them. Which is the rigth way?

emanuele
  • 2,519
  • 8
  • 38
  • 56

4 Answers4

5

You can do:

var arr = $(this).parent().find(':checkbox').map(function() {
    return this.checked;
}).get();

That'll get the bool array, if you just want to see if all the children are checked:

var areAllChecked = $(this).parent().find(':checkbox:not(:checked)').length === 0;
tymeJV
  • 103,943
  • 14
  • 161
  • 157
  • @Vohuman -- Realized that after re-reading - edited. – tymeJV Oct 22 '14 at 13:50
  • 1
    [Put the `get` immediately after the `find`, then replace `map` with `every`, and you're spot on](http://stackoverflow.com/a/26509036/356541). – Barney Oct 22 '14 at 13:51
2

if you want to check whether all are checked then test for if any are not checked and then negate it like

!$(this).parent().find(':checkbox').is(':not(:checked)')
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
  • very elegant solution to check if all children are selected. I choose the other answer because fit better with the title. – emanuele Oct 22 '14 at 14:07
1

I want check if all children checkbox are checked

I suppose you can use this syntax to accomplish that, rather than involving an array of booleans.

var allAreChecked = ($(this).parent().find(':checkbox').not(':checked').length === 0);
amphetamachine
  • 27,620
  • 12
  • 60
  • 72
1

Variation on tymeJV's answer:

$(this).parent().find(':checkbox').get().every(function(el){ return el.checked });

This simply gets the underlying array of element and uses every directly on that array to check the relevant property. It will return false is any checkbox fails this.checked.

Demo:

function allChecked(){
  return $(this).parent().find(':checkbox').get().every(function(el){
    return el.checked 
  });
}

$('button').on('click', function(){ alert( allChecked.call(this) ) })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<button>All checked?</button>
Community
  • 1
  • 1
Barney
  • 16,181
  • 5
  • 62
  • 76