Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

set variable if any checbox is checked

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">

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading