1

I have a bunch of forms with a checkbox in each of them and when a condition is met i want to disable every checkbox that is NOT checked.

I've tried doing this but with no luck

if (updateShowcasedProducts.length == 12) {                                    
 document.querySelectorAll('input[type="checkbox"]:not(:checked)').disabled = true;
    }

I would preferably only use vanilla javascript.

Chris
  • 51
  • 1
  • 5
  • 1
    Does this answer your question? [What do querySelectorAll and getElementsBy\* methods return?](https://stackoverflow.com/questions/10693845/what-do-queryselectorall-and-getelementsby-methods-return) – evolutionxbox Jan 12 '21 at 21:05

4 Answers4

6

querySelectorAll returns a NodeList object, you have to use that object to iterate through the elements and disable them.

if (updateShowcasedProducts.length == 12) {                                    
    document.querySelectorAll('input[type="checkbox"]:not(:checked)').forEach((element) => {
       element.disabled = true;
    });
}
Gunther
  • 1,297
  • 9
  • 15
2

You will need to loop through the results of querySelectorAll.

if (updateShowcasedProducts.length == 12) {                                    
    els = document.querySelectorAll('input[type="checkbox"]:not(:checked)');
    for (const el of els) {
      el.disabled = true;
    }
}
imvain2
  • 15,480
  • 1
  • 16
  • 21
2

You can first use a class for all those inputs what are checkboxes. And then use checked property:

let checkBoxes = document.getElementsByClassName("checkbox");
checkBoxes.forEach(checkBox)=>{
    if(!checkBox.checked){
          checkBox.disabled=true;
    };
});
b3lg1c4
  • 76
  • 1
  • 4
2

You can use something like this:

if (updateShowcasedProducts.length == 12) {
    document.querySelectorAll('input[type="checkbox"]').forEach(i => i.disabled = true);
}

Edit: I was too slow. Already suggested by @Gunther: https://stackoverflow.com/a/65692054/4261813

Dennis
  • 56
  • 7