Select multiple ID's - Both checkboxes must be selected

前端 未结 7 895
猫巷女王i
猫巷女王i 2021-02-07 03:37

Is there a way for two or more ID\'s be required to be checked before doing something.

For instance:

If BOTH Checkbox 1 and Checkbox 2 are checked then th

7条回答
  •  花落未央
    2021-02-07 03:57

    I would give both (or as many as you like) the same class='chk_option'. If you are using jQuery, then you could do this:

    function isSelectedBoth(){
        var result = true;
        $('.chk_option').each(function(){
            if(!$(this).is(':checked'))
                result=false;
        });
        return result;
    }
    

    When you are defining the on click events for each simply do this:

    $('.chk_option').change(function(e){
        if (isSelectedBoth()){
        // do something if both are selected
            alert('both checkboxes are selected');
        }else{
        // do something if not
            alert('You must select both checkboxes');
        }
    });
    

    You can do it even with smarter function then isSelectedBoth() where it could return something more useful then true/false, like order number of un/checked box, an array of elements un/checked etc.

提交回复
热议问题