Skip to content Skip to sidebar Skip to footer

Link Checkboxes With Parent/child Relationship Without Jquery

I'm not sure how to explain it. Hopefully my code is self-evident. I am fairly new to javascript.
closest() to find parent nodes by a selector.

https://caniuse.com/#search=closest

(You may have to click the GIF to get it to play.)

Example

<divdata-checkbox-group><label><inputtype="checkbox"data-master-checkbox /> Master</label><div><label><inputtype="checkbox" /> Check Box 1</label><br><label><inputtype="checkbox" /> Check Box 2</label><br><label><inputtype="checkbox" /> Check Box 3</label><br><label><inputtype="checkbox" /> Check Box 4</label><br><label><inputtype="checkbox" /> Check Box 5</label><br></div></div><hr><divdata-checkbox-group><label><inputtype="checkbox"data-master-checkbox /> Master</label><div><label><inputtype="checkbox" /> Check Box 1</label><br><label><inputtype="checkbox" /> Check Box 2</label><br><label><inputtype="checkbox" /> Check Box 3</label><br><label><inputtype="checkbox" /> Check Box 4</label><br><label><inputtype="checkbox" /> Check Box 5</label><br></div></div><hr><divdata-checkbox-group><label><inputtype="checkbox"data-master-checkbox /> Master</label><div><label><inputtype="checkbox" /> Check Box 1</label><br><label><inputtype="checkbox" /> Check Box 2</label><br><label><inputtype="checkbox" /> Check Box 3</label><br><label><inputtype="checkbox" /> Check Box 4</label><br><label><inputtype="checkbox" /> Check Box 5</label><br></div></div><hr><script>var toggleChecks = function() {
    var isMaster = this.hasAttribute('data-master-checkbox')
    var group = this.closest('[data-checkbox-group]')
    var boxes = group.querySelectorAll('input[type=checkbox]:not([data-master-checkbox])')
    var master = isMaster ? this : group.querySelector('input[type=checkbox][data-master-checkbox]')

    if (isMaster) {
      // Set all children to the value of the parentfor(var i = 0; i < boxes.length; i++) {
        boxes[i].checked = this.checked
      }
    } else {
      // Toggle all children to the state of the mastervar checkedCount = 0for(var i = 0; i < boxes.length; i++) {
        if(boxes[i].checked) { checkedCount += 1 }
      }

      master.checked = checkedCount == boxes.length
      master.indeterminate = !master.checked && !checkedCount == 0
    }
  }

  var nodes = document.querySelectorAll('[data-checkbox-group] input[type=checkbox]')
  for(var i = 0; i < nodes.length; i++) {
    nodes[i].addEventListener('change', toggleChecks)
  }
</script>

Post a Comment for "Link Checkboxes With Parent/child Relationship Without Jquery"