Home > Software design >  keep checkbox disabled and unchecked if any other two checkboxes are checked
keep checkbox disabled and unchecked if any other two checkboxes are checked

Time:02-18

I am trying to keep #b0 disabled and unchecked if #b1 and/or #b2 is/are checked. The snippet below re-enables #b0 if uncheck #b1 or #b2

let boxes = $('#b1, #b2');
boxes.click(function() {
    if (boxes.filter(':checked').length > 0) {
        $("#b0").prop("disabled", this.checked).prop({"checked": false}, this.checked);
    } 
})

<label for="b0">1</label>
<input id="b0" name="name0" type="checkbox">

<label for="b1">2</label>    
<input id="b1" name="name1" type="checkbox">

<label for="b2">3</label>
<input id="b2" name="name2" type="checkbox">

Fiddle

CodePudding user response:

You can enable the checkbox in an else block, like this:

let used_for_contact = $('#b1, #b2');
used_for_contact.click(function() {
  if (used_for_contact.filter(':checked').length > 0) {
    $("#b0").prop("disabled", true).prop("checked", false);
  } else {
    $("#b0").prop("disabled", false);
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<input id="b0" name="info_for_contact" type="checkbox">
<label for="b0">1</label>

<input id="b1" name="info_for_contact" type="checkbox">
<label for="b1">2</label>

<input id="b2" name="info_for_contact" type="checkbox">
<label for="b2">3</label>

Fiddle

  • Related