-1

I have set of checkboxes let's say 5. I want to set some variable on change to true if any checkbox is checked and if none variable shoudl stay falsy. What I wrote is similar but it changes variable all the time so I can check 3 checkboxes then uncheck 1 and variable will be falsy even tho there are checked checkboxes. I found some solutions but most of them run with one checkbox or use Jquery

 let button;
 let check_this = document.querySelectorAll('.check_this')

 Array.from(check_this).forEach(function(checbox){
        checbox.addEventListener("change", function(){
            if(checbox.checked){
                button = true
            }else{
                button = false
            }

        });
    });
<input class="check_this" type="checkbox" value="1">
<input class="check_this" type="checkbox" value="2">
<input class="check_this" type="checkbox" value="3">
<input class="check_this" type="checkbox" value="4">
<input class="check_this" type="checkbox" value="5">

1 Answers1

3

Use some() to check if at least one element has .checked

const onCheckboxChange = (event) => {
    let atLeastOneChecked = elements.some(e => e.checked);
    console.log('atLeastOneChecked:', atLeastOneChecked);
};

const elements = Array.from(document.querySelectorAll('.check_this'));
elements.forEach(e => e.addEventListener('change', onCheckboxChange));
<input class="check_this" type="checkbox" value="1">
<input class="check_this" type="checkbox" value="2">
<input class="check_this" type="checkbox" value="3">
<input class="check_this" type="checkbox" value="4">
<input class="check_this" type="checkbox" value="5" checked>
ColdIV
  • 1,118
  • 2
  • 13
  • 21
0stone0
  • 34,288
  • 4
  • 39
  • 64