Select multiple ID's - Both checkboxes must be selected

前端 未结 7 886
猫巷女王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 04:04

    Boolean logic ftw! So I'm pretty sure you're looking for what's known as the exclusive or, or XOR. This means that if just one and only one operand is true, the whole expression will be true. If neither operand is true or if both are true, the whole expression will evaluate as false. The operator for this is ^. So here's the code (borrowing from Chris as the basic format)...

    $('#checkbox1, #checkbox2').change(function() {
        if($('#checkbox1').is(':checked') && $('#checkbox2').is(':checked')) {
            // Both are checked
        }
        else if($('#checkbox1').is(':checked') ^ $('#checkbox2').is(':checked')) {
            // Exactly one is checked
        }
    });
    

    In reality, you only need an OR for the second if since we're using an else if and the first if covers when both are checked. But it's not as cool and obviously can't be used by itself to do the same thing (and is better for minifying *cough cough*).

    Enjoy!

提交回复
热议问题