bimacknyas
bimacknyas

Reputation: 37

How to uncheck checkbox if other checked using jquery

I have tried the below code to uncheck the 1st checkbox if any one of the below are checked. But not able to revert back to the initial stage i.e. if nothing is selected the first checkbox will checked.

$('ol input').on('click', function() {
  if(this.checked){  
    $('#all').prop('checked', false);
  }else{
    $('#all').prop('checked', true);
  }
});
ol li{list-style:none;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div>
  <input type="checkbox" id="all" checked>All
  <ol>
    <li>
      <input type="checkbox">1
      <input type="checkbox">2
      <input type="checkbox">3
      <input type="checkbox">4
      <input type="checkbox">5
    <li>
  </ol>
</div>

Upvotes: 0

Views: 506

Answers (1)

j08691
j08691

Reputation: 207861

Instead of your current else statement, try else if ($('ol input:checked').length == 0)

$('ol input').on('click', function() {
  if (this.checked) {
    $('#all').prop('checked', false);
  } else if ($('ol input:checked').length == 0) {
    $('#all').prop('checked', true);
  }
});
ol li {
  list-style: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div>
  <input type="checkbox" id="all" checked>All
  <ol>
    <li>
      <input type="checkbox">1
      <input type="checkbox">2
      <input type="checkbox">3
      <input type="checkbox">4
      <input type="checkbox">5
      <li>
  </ol>
</div>

Upvotes: 1

Related Questions