AbeIsWatching
AbeIsWatching

Reputation: 159

checking whether or not any checkbox input is checked from array of input

I have a node list of chechbox inputs

const searchSizeSelectionInputs = document.querySelectorAll(
  ".sizeHolderFilter > input")

I have written a function to check whether or not any checkbox is checked or not, the function is

const activationChecker = ()=>{
  if (
    availabilityInStoreOptions[0].classList.contains("activeSortOptionSP") ||
    availabilityInStoreOptions[1].classList.contains("activeSortOptionSP")
  ) {
    isAvailabilityInStorActive = true;
  }
  if(  !availabilityInStoreOptions[0].classList.contains("activeSortOptionSP") &&
    !availabilityInStoreOptions[1].classList.contains("activeSortOptionSP")) {
    isAvailabilityInStorActive = false;
  }
  searchSizeSelectionInputs.forEach(input => {
    if (input.checked) {
      isSizeInputChecked = true;
    } else {
      let isSizeInputChecked = false;
    }
  });
  searchColorSelectionInputs.forEach(input => {
    if (input.checked) {
      isColorInputChecked = true;
    } else {
      let isColorInputChecked = false;
    }
  });

};

the thing is, when I check the result of isSizeInputChecked or isColorInputChecked it gives me faulty answers, for example when I check the checkbox it gives me true and when I uncheck the checkbox it still gives me true, I tested the same code on one single object and it works beautifully,I believe I do have a problem on doing this on a node list. This must be the wrong way:

searchSizeSelectionInputs.forEach(input => {
    if (input.checked) {
      isSizeInputChecked = true;
    } else {
      let isSizeInputChecked = false;
    }

How can I check if any checkbox is checked or not any of them is checked?

Upvotes: 0

Views: 40

Answers (1)

vishnu sandhireddy
vishnu sandhireddy

Reputation: 1176

function getCheckedData() {
  let atleastOneChecked=Array.from(document.querySelectorAll('.checkbox'))
    .some(
      function(inputCheckbox) {
        return inputCheckbox.checked;
    }
 
);
let allChecked=Array.from(document.querySelectorAll('.checkbox'))
    .every(
      function(inputCheckbox) {
        return inputCheckbox.checked;
    }
 
);
console.log('atleastOneChecked',atleastOneChecked);
console.log('allChekecked',allChecked);

}
<input type="checkbox" class='checkbox'>
<input type="checkbox" class='checkbox'>

<button onclick="getCheckedData()">Get checked data</button>

The document.querySelectorAll returns a NodeList and it is not an array. We have to convert node list into an array using Array.from and use the some function from Array to get atleast one of the element is checked or not.

Upvotes: 1

Related Questions