Select/Deselect All Checkboxes Using jQuery - checkbox_all

Select/Deselect All Checkboxes Using jQuery - checkbox_all
File Size: 5.77 KB
Views Total: 253
Last Update:
Publish Date:
Official Website: Go to website
License: MIT
   

A dead-simple jQuery based Check All solution that enables a Master checkbox to select/deselect all child checkboxes in a group.

How to use it:

1. Insert a group of checkboxes into a container with the CSS class of js-check-all-target.

<ul class="js-check-all-target" data-check-all="language">
  <li class="item">
    <label class="label">
      <input type="checkbox" name="language" value="language1">
      <span class="text">JavaScript</span>
    </label>
  </li>
  <li class="item">
    <label class="label">
      <input type="checkbox" name="language" value="language2">
      <span class="text">Ruby</span>
    </label>
  </li>
  <li class="item">
    <label class="label">
      <input type="checkbox" name="language" value="language3">
      <span class="text">C++</span>
    </label>
  </li>
  <li class="item">
    <label class="label">
      <input type="checkbox" name="language" value="language4">
      <span class="text">Python</span>
    </label>
  </li>
</ul>

2. Create a Select All checkbox with the CSS class of js-check-all. Make sure that the data-check-all attribute of the Select All checkbox and checkbox group have the same value.

<label class="label">
  <input class="js-check-all" type="checkbox" name="" data-check-all="language">
  <span class="text">Check All</span>
</label>

3. The main jQuery script to enable the Select All checkbox. Copy and insert the following JS snippets after jQuery library.

<script src="/path/to/cdn/jquery.slim.min.js"></script>
$(function() {

  $('.js-check-all').on('change', function(event) {

    var group = $(event.target).data('check-all');

    var dataCheckGroup = '[data-check-all="' + group + '"]';


    if ($(event.target).prop('checked')) {

      $('.js-check-all-target')
        .filter(dataCheckGroup)
        .find('input[type="checkbox"]:not(:disabled)')
        .prop('checked', true);

        return;
    }

    $('.js-check-all-target')
      .filter(dataCheckGroup)
      .find('input[type="checkbox"]:not(:disabled)')
      .prop('checked', false);
  });
  
});

This awesome jQuery plugin is developed by it-web-life. For more Advanced Usages, please check the demo page or visit the official website.