Making sure at least one checkbox is checked

后端 未结 9 771
天命终不由人
天命终不由人 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

        <input type="checkbox" class="checkbox" value=ck1 /> ck1<br />
        <input type="checkbox" class="checkbox" value=ck2 /> ck2<br />
    
    

    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.

    0 讨论(0)
  • 2020-11-27 17:24

    Check this.

    You can't access form inputs via their name. Use document.getElements methods instead.

    0 讨论(0)
  • 2020-11-27 17:24

    Prevent user from deselecting last checked checkbox.
    jQuery (original answer).

    $('input[type="checkbox"][name="chkBx"]').on('change',function(){
        var getArrVal = $('input[type="checkbox"][name="chkBx"]:checked').map(function(){
            return this.value;
        }).toArray();
    
        if(getArrVal.length){
            //execute the code
            $('#msg').html(getArrVal.toString());
    
        } else {
            $(this).prop("checked",true);
            $('#msg').html("At least one value must be checked!");
            return false;
    
        }
    });
    

    UPDATED ANSWER 2019-05-31
    Plain JS

    let i,
        el = document.querySelectorAll('input[type="checkbox"][name="chkBx"]'),
        msg = document.getElementById('msg'),
        onChange = function(ev){
            ev.preventDefault();
            let _this = this,
                arrVal = Array.prototype.slice.call(
                    document.querySelectorAll('input[type="checkbox"][name="chkBx"]:checked'))
                        .map(function(cur){return cur.value});
    
            if(arrVal.length){
                msg.innerHTML = JSON.stringify(arrVal);
            } else {
                _this.checked=true;
                msg.innerHTML = "At least one value must be checked!";
            }
        };
    
    for(i=el.length;i--;){el[i].addEventListener('change',onChange,false);}
    <label><input type="checkbox" name="chkBx" value="value1" checked> Value1</label>
    <label><input type="checkbox" name="chkBx" value="value2"> Value2</label>
    <label><input type="checkbox" name="chkBx" value="value3"> Value3</label>
    <div id="msg"></div>

    0 讨论(0)
提交回复
热议问题