jQuery 选择多个 ID - 必须选中两个复选框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3190761/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 14:59:06  来源:igfitidea点击:

Select multiple ID's - Both checkboxes must be selected

jqueryjquery-selectors

提问by Mark H

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

有没有办法在做某事之前需要检查两个或多个 ID。

For instance:

例如:

If BOTHCheckbox 1 and Checkbox 2 are checked then the event happens.

如果BOTH复选框1和2复选框检查,则事件发生。

But if only 1 or the other are checked by themselves, something else happens.

但是如果自己只检查 1 个或另一个,就会发生其他事情。

I thought this would work but nope.

我以为这会奏效,但不行。

function toggleStatus() {
    if ($('#checkbox1 #checkbox2').is(':checked')) {
$('.option1 :input').attr('checked', true);
    } else {
$('.option1 :input').attr('checked', false);
}

function toggleStatus() {
    if ($('#checkbox1').is(':checked')) {
$('.option2 :input').attr('checked', true);
    } else {
$('.option2 :input').attr('checked', false);
}

function toggleStatus() {
    if ($('#checkbox2').is(':checked')) {
$('.option3 :input').attr('checked', true);
    } else {
$('.option3 :input').attr('checked', false);
}

Hopefully I am explaining this correctly. I have looked for three days and I am stuck. Thanks for any help!

希望我能正确解释这一点。我找了三天,卡住了。谢谢你的帮助!

回答by Chris Forrette

$('#checkbox1, #checkbox2').change(function() {
   if ($('#checkbox1').is(':checked') && $('#checkbox2').is(':checked')) {
       // Do some stuff if both boxes are checked...
   }
});

回答by Pluto

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)...

布尔逻辑 ftw!所以我很确定您正在寻找所谓的异或或异或。这意味着如果只有一个且只有一个操作数为真,则整个表达式将为真。如果两个操作数都不为真或两者都为真,则整个表达式将评估为假。这个操作符是^。所以这是代码(从 Chris 借来作为基本格式)...

$('#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 ifsince we're using an else ifand the first ifcovers 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*).

实际上,您只需要一个 OR 作为第二个,if因为我们使用的是一个else if和第一个if封面,当两者都被检查时。但它没有那么酷,显然不能单独用来做同样的事情(而且更适合缩小*咳咳*)。

Enjoy!

享受!

回答by spinon

I would give the checkboxes a common class. Then use that as the selector and count the checked values. Then if two are checked do something. If one is checked then check the value of that one and do what you need to accordingly.

我会给复选框一个通用类。然后将其用作选择器并计算选中的值。然后,如果检查了两个,请执行某些操作。如果选中了一个,则检查该值的值并相应地执行您需要的操作。

EDIT: So say for instance you assigned a common class of myCheckBoxes

编辑:所以说例如你分配了一个常见的 myCheckBoxes 类

So you could do the following pseudo code:

因此,您可以执行以下伪代码:

var myCheckBoxes = $('.myCheckBoxes:checked') //not sure on selector

if (myCheckBoxes.length == 2)
    //do something because both are checked
else if (myCheckBoxes.length == 1)
{
    if (myCheckBoxes.val() == "A")
        // do something because A was checked
    else if (myCheckBoxes.val() == "B")
        // do something because B was checked
}

回答by tiffon

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:

如果复选框被某个元素包裹:

<div class="check-group">
    <label><input id="checkbox1" type="checkbox"> one </label>
    <label><input id="checkbox2" type="checkbox"> two </label>
</div>

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');
        }
    });
});

回答by Sasa

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:

我会给两者(或您喜欢的数量)相同的 class='chk_option'。如果您使用的是 jQuery,那么您可以这样做:

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.

您甚至可以使用比 isSelectedBoth() 更智能的函数来完成它,它可以返回比真/假更有用的东西,例如未/选中框的订单号、未/选中的元素数组等。

回答by Germán Rodríguez

$(document).ready(function() {
   var check1 = $("#check1");
   var check2 = $("#check2");

   // this method decides what to do when a checkbox is clicked
   var trigger_event = function() {
        if (check1.attr("checked") && check2.attr("checked")) {
            event1();
        }
        else if (check1.attr("checked") && !check2.attr("checked")) {
            event2();
        }
        else if (!check1.attr("checked") && check2.attr("checked")) {
            event3();
        }
   };

   // append event
   check1.click(function() {
       trigger_event();
   });

   check2.click(function() {
      trigger_event();
   });

};

回答by user2314737

There are two issues in your code:

您的代码中有两个问题:

  1. you're using $('#checkbox1 #checkbox2')to select the two checkboxes, but without a comma that's an “ancestor descendant” selectorand not a multiple selector

  2. the is()operator returns trueif at least oneof the selected elements matches the given arguments. So, if you use if ($('#checkbox1, #checkbox2').is(':checked'))this is true whenever either one (but not necessarily both) checkboxes are checked

  1. $('#checkbox1 #checkbox2')用来选择两个复选框,但没有逗号,它是“祖先后代”选择器而不是多重选择器

  2. 如果所选元素中至少有一个与给定参数匹配,则is()运算符返回。因此,如果您在选中其中一个(但不一定两个)复选框时使用此选项,则为 truetrueif ($('#checkbox1, #checkbox2').is(':checked'))

So, in order to do something when bothcheckboxes are checked you need to use is(':checked')on both separately, as in the top-voted answer.

因此,为了选中两个复选框时执行某些操作,您需要is(':checked')分别在两者上使用,如投票最高的答案

Here is a demo showing is()behavior

这是一个显示is()行为的演示

$('input').on('change', function(ev) {
  if ($('#checkbox1, #checkbox2').is(':checked')) {
    console.log("is(':checked') true because at least one is checked");
  } else {
    console.log("is(':checked') not true");
  };
  if ($('#checkbox1').is(':checked') && $('#checkbox2').is(':checked')) {
    console.log("both checked");
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<label><input type="checkbox" id="checkbox1"/>checkbox1<label>
<label><input type="checkbox" id="checkbox2"/>checkbox2</label>