Making sure at least one checkbox is checked

后端 未结 9 815
天命终不由人
天命终不由人 2020-11-27 16:39

I have a form with multiple checkboxes and I want to use JavaScript to make sure at least one is checked. This is what I have right now but no matter what is chosen an alert

9条回答
  •  北荒
    北荒 (楼主)
    2020-11-27 17:20

    I would opt for a more functional approach. Since ES6 we have been given such nice tools to solve our problems, so why not use them. Let's begin with giving the checkboxes a class so we can round them up very nicely. I prefer to use a class instead of input[type="checkbox"] because now the solution is more generic and can be used also when you have more groups of checkboxes in your document.

    HTML

         ck1
    ck2

    JavaScript

    function atLeastOneCheckboxIsChecked(){
        const checkboxes = Array.from(document.querySelectorAll(".checkbox"));
        return checkboxes.reduce((acc, curr) => acc || curr.checked, false);
    }
    

    When called, the function will return false if no checkbox has been checked and true if one or both is.

    It works as follows, the reducer function has two arguments, the accumulator (acc) and the current value (curr). For every iteration over the array, the reducer will return true if either the accumulator or the current value is true. the return value of the previous iteration is the accumulator of the current iteration, therefore, if it ever is true, it will stay true until the end.

提交回复
热议问题