Select multiple ID's - Both checkboxes must be selected

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

    var ids = ['#checkbox1', '#checkbox2'],
        $chx = $(ids.join(',')),
        count = $chx.length;
    
    $chx.on('change', function() {
        if ($chx.filter(':checked').length === count) {
            // do stuff
            console.log('all true');
        }
    });
    

    If the checkboxes are wrapped by some element:

    Then the wrapping element can have the event listener:

    $('.check-group').each(function() {
    
        var $this = $(this),
            $chx = $this.find('input[type=checkbox]'),
            count = $chx.length;
    
        if (count === 0) {
            return;
        }
    
        $this.on('change', function() {
            if (count === $chx.filter(':checked').length) {
                console.log('all checked');
            }
        });
    });
    

提交回复
热议问题