Select multiple ID's - Both checkboxes must be selected

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

    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” selector and not a multiple selector

    2. the is() operator returns true if at least one of 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

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

    Here is a demo showing is() behavior

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

提交回复
热议问题