Home > Blockchain >  jQuery keep checkbox checked while any others are checked
jQuery keep checkbox checked while any others are checked

Time:02-12

I have more than fifteen checkbox inputs all with the same class, looking something like below:

I want to have only the first input be checked and stay checked when any other input with the same class is checked. If only the first input is checked you should be able to check and uncheck it freely. Only the first one has the ID, #SR01201. The rest only have the class check-12.

Right now, I can freely uncheck and check the first input, and it will get checked if any other inputs with the class check-12 are checked. But once any other input (besides the first one) is checked, it can't be unchecked.

$('.check-12:not(#SR01201)').on('change', function() {
  var $this = $(this);
  var SRTwelveOne = $("#SR01201");
  if ($this.prop('checked', true)) {
    SRTwelveOne.prop('checked', true)
  } else if ($this.prop('checked', false) && $this.siblings().prop('checked', false)) {
    SRTwelveOne.prop('checked', false);
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" name="SR-012-01" value="SR-12-01"  id="SR01201">
<input type="checkbox" name="SR-012-02" value="SR-12-02" >
<input type="checkbox" name="SR-012-03" value="SR-12-03" >

CodePudding user response:

The problem is that you're not checking if a checkbox is checked with $this.prop('checked', true) in your if statement. You're actually checking the box. To see if it's a box is checked, use is(":checked")

CodePudding user response:

The $this.prop('checked', true) in if ($this.prop('checked', true)) is setting the checkbox to true, not checking if it's true. For that you want to use if ($this.prop('checked')). But I think your issue can be reduced to the following:

$('.check-12:not(#SR01201)').on('change', function() {
  $("#SR01201").prop('checked', $('.check-12:not(#SR01201):checked').length > 0);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" name="SR-012-01" value="SR-12-01"  id="SR01201">
<input type="checkbox" name="SR-012-02" value="SR-12-02" >
<input type="checkbox" name="SR-012-03" value="SR-12-03" >

The first line selects your checkboxes with the class you specified, but not the first one. Upon changing any of them, the checkbox with the ID SR01201 changes its checked property depending on how many of the other checkboxes are checked. 1 or more? check it, otherwise uncheck it. The result of $('.check-12:not(#SR01201):checked').length > 0 will be true or false.

  • Related