cstrap
1/23/2013 - 5:02 AM

For when you need a master checkbox, that will cause others to be checked.

For when you need a master checkbox, that will cause others to be checked.

/*
  Use like this (or with <dl>, <ol>, <table>)...

  <ul>
    <li>
      <input type="checkbox" class="check-all" />
    </li>
    <li>
      <input type="checkbox" />
    </li>
    <li>
      <input type="checkbox" />
    </li>
  </ul>
*/


// Module pattern
var check_all = (function($, window, document, undefined) {
  // Kickoff
  $(document).ready(function() {
    check_all.init();
  });

  // Expose publicly
  return {
    // check_all.init
    init: function() {
      // Run on DOM load, and click
      function determine_checked(el) {
        var parent = el.closest('dl, ol, table, ul');
        var master = parent.find('input[type="checkbox"].check-all');

        // Exit, if no "check-all" exists
        if (!master.length) {
          return;
        }

        var others = parent.find('input[type="checkbox"]').not('.check-all');
        var others_checked = others.filter(':checked');

        // Is this the master checkbox?
        if (el.hasClass('check-all')) {
          // Is it checked?
          if (el.prop('checked')) {
            // Check all
            others.prop('checked', true);
          }
          else {
            // Un-check all
            others.prop('checked', false);
          }
        }
        // Must be a sibling checkbox
        else {
          // Are all siblings checked?
          if (others.length === others_checked.length) {
            // Check master
            master.prop('checked', true);
          }
          else {
            // Un-check master
            master.prop('checked', false);
          }
        }
      }

      $(document.documentElement).off('click.check_all').on('click.check_all', 'input[type="checkbox"]', function() {
        var el = $(this);
        determine_checked(el);
      });

      $('input[type="checkbox"].check-all').each(function() {
        var el = $(this);
        determine_checked(el);
      });
    }
  };
})(jQuery, this, this.document);