King David King David - 2 months ago 12
jQuery Question

Jquery Checkbox That Checks List Below It

I want to build a jquery function or onclick event which checks all checkbox if you click on the middle list and uncheck all checkbox above its list.

To explain futher, example I have 5 checkbox:

Checkbox 1
Checkbox 2
Checkbox 3
Checkbox 4
Checkbox 5


First scenario:

If I click Checkbox 3, all checkbox below will all be checked which is Checkbox 4 & Checkbox 5.

Second scenario:

If I uncheck Checkbox 3, all Checkbox 3,4 and 5 will be unchecked as well.

Answer

You may use the change event so that every time a checkbox changes its value you may set this new value (checked, unchecked) for the remaining elements:

//
// When a checkbox changes its value do....
//

$(':checkbox').on('change', function(e) {
  //
  // get current value: checked/unchecked
  //
  var chk = this.checked;
  
  //
  // get all next checkbox elements and set their values
  // to the current value: checked/unchecked
  //
  // $(this).nextAll(':checkbox').prop('checked', chk);

   // UPDATE
  //
  // get all next checkbox elements and set their values
  // to the current value: checked/unchecked
  //
  if (chk == true) {
    $(this).nextAll(':checkbox').prop('checked', chk);
  } else {
    $(this).siblings(':checkbox').prop('checked', chk);
  }
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<form>
    <input type="checkbox" name="vehicle" value="1">1<br>
    <input type="checkbox" name="vehicle" value="2">2<br>
    <input type="checkbox" name="vehicle" value="3">3<br>
    <input type="checkbox" name="vehicle" value="4">4<br>
    <input type="checkbox" name="vehicle" value="5">5<br>
</form>

Comments