1

I am checking each checkbox status (2 elements in total).

var checked = [];
document.querySelectorAll('.checkbox').forEach(function(e,i){
 checked.push(e.checked)
})

Now checked value could be

(2) [true, true]

or

(2) [true, false]

or

(2) [false, true]

or

(2) [false, false]

I am now checking it with a little bit manual way

if(checked[0] && check[1]) { ... }

If I have more elements, I have to add them manually like

 if(checked[0] && check[1] && check[2]) { ... }

I am seeking a better way to polish my code, so I don't need to manually add array values to compare. Thanks

2
  • You want to check if all are true or not? Commented Apr 4, 2018 at 11:30
  • Yes, I'd like to check if all true Commented Apr 4, 2018 at 11:31

3 Answers 3

5

Use every and Array.from

var checked = [];
var allCheckboxes = document.querySelectorAll('.checkbox');
var allChecked = Array.from( allCheckboxes ).every( s => s.checked )
Sign up to request clarification or add additional context in comments.

3 Comments

ah! yes! every Thank you very much
just checked developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… IE doesnt support from Is there a way to support IE and some mobile browsers ? Thanks
0

You can use Array.reduce to do that like this

const pass = [true, true, true]
const passNot = [true, false, true]

const reducer = (isPassing, value) => {
  if (value === false) return false
  else return isPassing
}

console.log('yay', pass.reduce(reducer, true))
console.log('nay', passNot.reduce(reducer, true))

1 Comment

This method supports IE and most of mobile browsers! Many thanks!
0

You are tryng to combine an array of values into a single one, thats what the reduce method does.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

    let result = document.querySelectorAll('.checkbox')
    .map( box => box.checked ) // get an array of boolean
    .reduce ( (bool, res) => return bool && res /*all checkboxes must be checked */, true /* initial value */ );

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.